2 回答
TA贡献1875条经验 获得超3个赞
您使用了错误的事件侦听器。文本输入应使用“键控”,而不是“更改”
document.getElementById('username').addEventListener('keyup', buildLinkRefs );
因此,使用您的代码,它应该如下所示:
function el(elementId, username, action) {
document.getElementById(elementId).setAttribute("href", "skype:" + username + "?" + action);
}
function buildLinkRefs() {
var username = document.getElementById("username").value;
el("call-btn", username, "call");
el("add-to-contacts-btn", username, "add");
el("view-profile-btn", username, "userinfo");
el("voice-email-btn", username, "voicemail");
el("chat-btn", username, "chat");
el("sendfile-btn", username, "sendfile");
}
document.getElementById("username").addEventListener("keyup", buildLinkRefs );
buildLinkRefs();
<input type="text" id="username" value="echo123"/><br>
<br>
<a id="call-btn">Call</a> <br>
<a id="add-to-contacts-btn">Add to contacts</a> <br>
<a id="view-profile-btn">View User Profile</a> <br>
<a id="voice-email-btn">Voice Email</a> <br>
<a id="chat-btn">Start Chat</a> <br>
<a id="sendfile-btn">Send File</a> <br>
TA贡献1784条经验 获得超8个赞
问题是,您的函数在加载整个页面之前被触发,因此它看不到该元素,因为该元素不可用 。因此,有很多方法可以解决它 。只需将代码放在html元素之后或下方,如下所示:username
<html>
<head>
<title>the title</title>
</head>
<body>
<input type="text" id="username" value="echo123"/><br>
<br>
<a id="call-btn">Call</a> <br>
<a id="add-to-contacts-btn">Add to contacts</a> <br>
<a id="view-profile-btn">View User Profile</a> <br>
<a id="voice-email-btn">Voice Email</a> <br>
<a id="chat-btn">Start Chat</a> <br>
<a id="sendfile-btn">Send File</a> <br>
<!-- ### PLACE HERE YOUR CODE AFTER YOUR HTML CONTENT -->
<script type="text/javascript" language="javascript">
function el(elementId, username, action) {
document.getElementById(elementId).setAttribute("href", "skype:" +
username + "?" + action);
}
function buildLinkRefs() {
var username = document.getElementById("username").value;
el("call-btn", username, "call");
el("add-to-contacts-btn", username, "add");
el("view-profile-btn", username, "userinfo");
el("voice-email-btn", username, "voicemail");
el("chat-btn", username, "chat");
el("sendfile-btn", username, "sendfile");
}
document.getElementById("username").addEventListener("change", function () {
buildLinkRefs();
}, false);
buildLinkRefs();
</script>
添加回答
举报