jQuery click事件没有响应

nar*_*mar 0 javascript jquery

我有一个jQuery点击事件的简单问题,我无法解决.

这是代码:

$('document').ready(function() {
    var links = $('.brandLinks li a');
    console.log(links.length); // there are total 24 items are there

    for(var i = 0; i < links.length; i++) {
        links[i].click(function(e){
            console.log('click.');
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

Jam*_*ice 6

你不需要循环.大多数jQuery方法将对匹配集中的每个项进行操作.另外,document不应该引用.您想要选择实际document对象.如果它被引用,jQuery将寻找标签名为"document"的元素:

$(document).ready(function() {
    $('.brandLinks li a').click(function () {
        console.log('click');
    });
});
Run Code Online (Sandbox Code Playgroud)

旁注:在这种情况下,字符串"document"与任何内容都不匹配并不重要.该ready方法将对任何jQuery对象进行操作,无论它包含什么(即使它是空的).对于其他人来说,阅读你的代码(以及将来你自己)来实际选择document对象会更有意义.出于这些原因,我通常使用替代形式:

$(function () {
    // This is the same as $(document).ready(function () {});
});
Run Code Online (Sandbox Code Playgroud)