While loop in jquery of dynamic id and class

僤鯓⒐⒋嵵緔 提交于 2019-12-25 06:46:15

问题


I have have multiple divs' with similar code within it, but also has a unique id within the main div that calls a toggleClass & slideToggle function. I'm trying to create a loop so that I do not have to write similar code for each element.

--- working code --- (where numeric value after the id would change)

$('#er1').click(function() {
    $('#er1').toggleClass('but-extra-on');
    $('#cr1').toggleClass('but-closerow-on');
    $('#er1').next('div').slideToggle('slow');
    return false;
});

-- not working code -- (I want to have functions for the click of #er1, #er2, #er3 etc.)

var count = 1;
while (count < 10){
    var curER = 'er'+count; 
    var curCR = 'cr'+count; 
    $('#'+curER).click(function() {
        $('#'+curER).toggleClass('but-extra-on');
        $('#'+curCR).toggleClass('but-closerow-on');
        $('#'+curER).next('div').slideToggle('slow');
    });
    count++;
}

* for some reason, when I use the while code, whenever I click #er1, #er2, #er3 etc.. only the event for #er9 toggles.


回答1:


You can solve this problem, by using the $(this) selector for the one that you are clicking, and attaching an html data attribute to the div, specifying the other div that you want to change when you click it and selecting the other one with that... make sense.. probably not? Check out Solution 1 below.

The second solution is to use jQuery Event Data to pass the count variable into the event listener.

Solution 1: http://jsfiddle.net/Es4QW/8/ (this bloats your html a bit)
Solution 2: http://jsfiddle.net/CoryDanielson/Es4QW/23/

I believe the second solution is slightly more efficient, because you have slightly less HTML code, and the $(this) object is slightly smaller. Creating the map and passing it as event data, I believe, is less intensive... but... realistically... there's no difference... the second solution has cleaner HTML code, so you should use that.

Solution 3 w/ .slideToggle(): http://jsfiddle.net/CoryDanielson/Es4QW/24/

Edit: Updated solutions by passing in the selected elements instead of the selectors. Now each click event will not do a DOM lookup as it did before.




回答2:


I've run into this problem before. I fixed it by extracting the event listener code into its own function like so:

for (var i = 1; i < 10; i++) {
    attachClickEvent('er'+i, 'cr'+i);
)

function attachClickEvent(cr, er)
{
    $('#'+er).click(function() {
        $(this).toggleClass('but-extra-on');
        $('#'+cr).toggleClass('but-closerow-on');
        $(this).next('div').slideToggle('slow');
    });
}


来源:https://stackoverflow.com/questions/7999668/while-loop-in-jquery-of-dynamic-id-and-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!