我的带有 addEventHandler/click 的 JS 代码不起作用?
<script>
var counter = 0;
//Loads all the elements and assigns event handlers
function load()
{
//create and append prev button
loadPeople(counter);
var btnNext = document.createElement("div");
btnNext.setAttribute("class", "button");
btnNext.setAttribute("id", "n");
btnNext.innerHTML = "Next"
root.appendChild(btnNext);
}
function loadPeople(index)
{
//This creates and appends several boxes with photos to represent various people
}
function addListeners()
{
//Add listeners
//Previous
//Next
var eventNextClick = document.getElementById("n");
eventNextClick.addEventListener("onclick", next, true);
}
//This should fire when next button is clicked
function next()
{
alert("This works");
}
document.addEventListener("DOMContentLoaded", load, false)
addListeners();
</script>
基本上......我的代码生成两个按钮上一个和下一个,以及几个显示图像的框。忽略这些框,现在,我只是想让点击事件起作用。
这段代码似乎没有产生任何可点击的内容。不确定我的问题出在哪里。请解释你的答案。
<script>
var counter = 0;
//Loads all the elements and assigns event handlers
function load()
{
//create and append prev button
loadPeople(counter);
var btnNext = document.createElement("div");
btnNext.setAttribute("class", "button");
btnNext.setAttribute("id", "n");
btnNext.innerHTML = "Next"
root.appendChild(btnNext);
}
function loadPeople(index)
{
//This creates and appends several boxes with photos to represent various people
}
function addListeners()
{
//Add listeners
//Previous
//Next
var eventNextClick = document.getElementById("n");
eventNextClick.addEventListener("onclick", next, true);
}
//This should fire when next button is clicked
function next()
{
alert("This works");
}
document.addEventListener("DOMContentLoaded", load, false)
addListeners();
</script>
Basically...my code generates two buttons prev and next, and several boxes that show images. Disregard the boxes, right now, I am just trying to get the click event to work.
This code does not seem to produce anything clickable. Not sure where my problem is. Please explain your answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
onclick
应该只是click
。但请记住,在< IE9,使用
attachEvent()
时使用on
前缀。The
onclick
should just beclick
.Remember though, in < IE9, when using
attachEvent()
to use theon
prefix.eventNextClick.addEventListener("onclick", next, true);
您需要使用
"click"
而不是"onclick"
您可能还想将第三个参数设置为 false,因为默认情况下您要使用冒泡。
您还可以在绑定 DOM 就绪事件后直接添加侦听器。这行不通。您需要等到
load
触发并生成按钮,然后才能调用addListeners
eventNextClick.addEventListener("onclick", next, true);
You need to use
"click"
not"onclick"
You probably also want to set the third parameter to
false
since by default you want to use bubbling.Your also adding listeners directly after binding the DOM ready event. This wont work. You need to wait until
load
has fired and until the button has been generated before you invokeaddListeners