繁体   English   中英

querySelectorAll不起作用?

[英]querySelectorAll not working?

这是我的JavaScript代码:

function answer(){
var list = document.querySelectorAll("#fish");
list[1].onclick = talk();
}

function talk(){
alert('hello!');
}

window.onload = answer();

运行时,它会弹出警告提示为“ hello”的浏览器窗口。 我的html代码:

<!DOCTYPE html>
<html>
<head>
<title>my site</title>
<script src="new 3x.js"></script>
</head>
<body>
<section>
<p id="fish">hello world!</P>
<p id="fish">tuna</P>
<p id="stuff">durr</P>
</section>
</body>
</html>

它在加载选项卡时向您发出警告。而当我单击金枪鱼时,我希望它运行时发出警告!

您没有正确分配事件处理程序-您分配的是调用函数的结果 ,而不是函数本身。 删除()

function answer(){
var list = document.querySelectorAll("#fish");
list[1].onclick = talk;
}

function talk(){
alert('hello!');
}

window.onload = answer;

当前正在发生的是,只要window.onload = answer(); 线被击中,您将立即运行answer功能。 当它到达onclick行时,它立即调用talk功能。 那不是你想要的。

如果使用ID,为什么要首先使用querySelectorAll? 只需使用getElementById。

var list = document.getElementById("fish");
list.addEventListener('click', talk, false);

编辑

现在,我看到您使用的是非唯一ID,我认为这是不好的做法。 为什么不只使用班级fish呢?

<p class="fish">hello world!</P>
<p class="fish">tuna</P>
<p id="stuff">durr</P>

然后像这样选择:

var list = document.querySelectorAll(".fish");
list[0].addEventListener('click', talk, false);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM