简体   繁体   English

JavaScript:addEventListener未运行

[英]JavaScript: addEventListener not running

Learning Javscript and trying to trigger a click event. 学习Javscript并尝试触发click事件。

I'm not sure what I'm doing wrong but the following doesn't seem to work. 我不确定自己在做什么错,但是以下操作似乎无效。

JSFiddle 的jsfiddle

http://jsfiddle.net/73e7H/1/ http://jsfiddle.net/73e7H/1/

HTML HTML

<ul>
    <li id="nav-item-39">
        <a href="#">Visit</a>
    </li> 
<ul>

JS JS

var $visit = document.getElementById('nav-item-39').firstChild;

$visit.addEventListener('click', function() {
    print('hello');
});

The firstChild is a text node containing the whitespace after the end of the li start tag and the beginning of the link. firstChild是一个文本节点,在li start标记的末尾和链接的开头之后包含空白。 You need the first child that's an element . 您需要的第一个孩子是element

On many browsers, that's firstElementChild , but if you need support for older browsers you may need a loop. 在许多浏览器中,这是firstElementChild ,但是如果您需要对旧版浏览器的支持,则可能需要循环。

Fiddle (using alert rather than print ) 小提琴 (使用alert而不是print

Another option is to use querySelector , which is available on all modern browsers (even IE8 — but of course, IE8 doesn't have addEventListener ): 另一个选择是使用querySelector ,它在所有现代浏览器(甚至是IE8中都可用),但是IE8当然没有addEventListener

var $visit = document.querySelector('#nav-item-39 a');

$visit.addEventListener('click', function() {
    print('hello');
});

That finds the first a element that's a descendant of #nav-item-39 . 这样会找到第a元素, a元素是#nav-item-39的后代。 If you want to require that it's a direct child instead, use the selector string "#nav-item-39 > a" instead. 如果您想要求它是直接子代 ,请改用选择器字符串"#nav-item-39 > a"

Fiddle 小提琴

(Just for completeness: querySelector finds the first matching element and returns it [or null if no match]. There's also querySelectorAll which finds all matching elements and returns a static NodeList .) (仅出于完整性考虑: querySelector查找第一个匹配的元素并返回它(如果没有匹配,则返回null如果还有,则是querySelectorAll ,它查找所有匹配的元素并返回一个静态NodeList 。)


Side note: print , unless you override it (and I don't think you do in the fiddle), is window.print which opens the browser's Print dialog. 旁注: printwindow.print ,除非您将其覆盖(除非您不做作,否则它会打开),它会打开浏览器的“打印”对话框。

Try Using firstElementChild instead of firstChild. 尝试使用firstElementChild代替firstChild。 firstElementChild will defenitely return element, when firstChild can return text node also. 当firstChild也可以返回文本节点时,firstElementChild将默认返回元素。

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

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