简体   繁体   中英

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>

No alert box when the link is clicked. UPDATE:
I have more than 1 id. I have shown only one to simplify the problem.

You could further simplify it to:

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

You will have to use String.toString() to get the value of the String object.

It´s not clear why you would need an array of selectors but here are two solutions;

Your solution using 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
    });
});

Alternative solution using 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
});

See my demo .

If you don´t really need the array of selectors I would recommend a simple multiple selector like this;

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

Firstly, why are you using a foreach construct when iterating over an id? When you are using and id, there is supposed to be EXACTLY ONE element with the given id. So, this should be fine:

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

Secondly, each iterates over an array, your array being #clk . Just the string, nothing else. All your function gets is two parameters: 0' (the index of the element) and the string #clk` (the value at that index). The string IS NOT resolved to a JS object.

IMO, the cleanest way to solve your problem statement would be:

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

The ^= selector would select all anchors whose id starts with 'clk' and bind the click function to all of those. You can read more about this selector here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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