动态ID和类的jquery中的while循环 [英] While loop in jquery of dynamic id and class

查看:74
本文介绍了动态ID和类的jquery中的while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个带有相似代码的div,但在主div中也有一个唯一的ID,该ID调用toggleClass& slideToggle函数.我正在尝试创建一个循环,这样我就不必为每个元素编写类似的代码.

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.

---工作代码---(其中ID后面的数字会更改)

--- 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;
});

-不起作用的代码-(我想具有单击#er1,#er2,#er3等的功能)

-- 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++;
}

* 由于某种原因,当我使用while代码时,每当我单击#er1,#er2,#er3等时,只有#er9的事件才会切换.

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

推荐答案

您可以通过以下方法解决此问题:使用$(this)选择器作为您要单击的选择器,并将html数据属性附加到div,指定当您单击另一个div并选择另一个div时,您想更改它.请查看下面的解决方案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.

第二种解决方案是使用 jQuery事件数据将count变量传递到事件中听众.

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

解决方案1: http://jsfiddle.net/Es4QW/8/(这会使您的html有点膨胀)
解决方案2: http://jsfiddle.net/CoryDanielson/Es4QW/23/

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

我相信第二种解决方案效率更高,因为您的HTML代码略少,而$(this)对象略小.我相信,创建地图并将其作为事件数据传递不会太费劲...但是...实际上...没有什么区别... the second solution has cleaner HTML code, so you should use that.

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.

带有.slideToggle()的解决方案3: http://jsfiddle .net/CoryDanielson/Es4QW/24/

通过传入选定的元素而不是选择器来更新解决方案.现在,每个click事件都不会像以前那样进行DOM查找.

这篇关于动态ID和类的jquery中的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆