繁体   English   中英

这个jQuery $ .each()代码有什么问题?

[英]What's wrong in this jquery $.each() code?

使用Javascript

 $.each(['#clk','#clk1'], function()
    {
        $(this).click(function () {
            alert("click")
        });
    });

HTML

   <a href="#" id="clk">click me</a>
   <a href="#" id="clk1">click me</a>

单击链接时没有警报框。 更新:
我有1个以上的ID。 我只显示了一个以简化问题。

您可以将其进一步简化为:

$("#clk").click (function () {
    alert("click");
});

您将必须使用String.toString()来获取String对象的值。

目前尚不清楚为什么需要选择器数组,但这是两个解决方案。

您使用String.toString()解决方案;

// Array of strings to be used as element selectors.
var selectors = ['#element1', '#element2'];

// Using $.each()
$.each(selectors, function() {
    // String.toString() returns the value of the String object.
    var $this = $(this.toString());

    $this.click(function () {
        console.log('Clicked element(1) =', this.id || this); // DEBUG
    });
});

使用String.join()替代解决方案;

// Using String.join()
$(selectors.join(',')).click(function(event) {
    event.preventDefault(); // This is to not follow the link

    // Notice that "this" now referes to the current/clicked element 
    // and not any string value from the "selectors" array.
    console.log('Clicked element(2) =', this.id || this); // DEBUG
});

看我的演示

如果您真的不需要选择器数组,我建议您使用一个简单的多重选择器,例如:

$('#element1, #element2').click(function() { ... });

首先,为什么遍历一个id时为什么要使用一个foreach构造? 当您使用and id时,应该是具有给定id的EXACTLY一个元素。 因此,这应该很好:

$("#clk").click(function() {
    alert("click");
});

其次,每个迭代遍历一个数组,您的数组是#clk 只是字符串,没有别的。 您获得的所有功能是两个参数: 0' (the index of the element) and the string #clk`(该索引处的值)。 字符串未解析为JS对象。

IMO,解决您的问题陈述的最干净的方法是:

$("a[id^='clk']").click(function () {
        alert("click");
});

^=选择器将选择所有ID以'clk'开头的锚,并将click函数绑定到所有锚。 您可以在此处了解有关此选择器的更多信息

暂无
暂无

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

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