簡體   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