divs jquery之间如何迭代

问题描述

| 我对如何迭代到div组存有疑问,我的问题是我有此选择器
$(\'.imagePanel\')
该选择器给出一组属于该类的div。我也知道使用方法
length
我可以知道div的程度。问题是我想知道是否可以在每个div中存储一个数组以了解它是用户单击的div,换句话说就是
$(\".imagePanel\").click(setElement);

function setElement() {

for (var i = 0; i < $(\'.imagePanel\').length; i++) {

    //validate in the loop if it\'s in the div that click the user
    if (this.id == $(\"#\"i).id) {

        if (!$(this).data(\'selected\')) {
            $(this).css(\'border\',\'2px solid black\').data(\'selected\',true);
        }
        else {
            $(this).stop(true,true).data(\'selected\',false);
        }
    }

}
}
编辑 更具体地说,在div组中,我只需要一个具有样式,如果您单击一个,然后单击另一个,则单击的最后一个div是具有另一个div样式的一个需要清除样式 不想这个     

解决方法

        要回答更新后的问题(请参阅问题注释行),您不需要遍历所有div。 只需将函数绑定到
click
,即可将所需的CSS类添加到to4ѭ(单击的元素)。 确保仅选择一项的一种方法是保留当前所选元素的缓存,并在单击其他内容时从中删除关联的类。 例:
var selected_xyz = null; 
$(\'.xyz\').click(function() {
    t = $(this);
    if (selected_xyz != t) {
        if (selected_xyz != null) {
           selected_xyz.removeClass(\"selected\");   
        }
        t.addClass(\"selected\");
        selected_xyz = t;
    }
});
演示:http://jsfiddle.net/LS4JV/1/     ,        
this
将获得您要单击的元素:
$(\".imagePanel\").click(function(){
    var $this = $(this); //<--good practice: cache
    if (!$this.data(\'selected\')) {
        $this.css(\'border\',\'2px solid black\').data(\'selected\',true);
    } else {
        $this.stop(true,true).data(\'selected\',false);
    }
});
您可以将以上内容重构,以更简洁:
$(\".imagePanel\").click(function(){
    var $this = $(this); //<--good practice: cache
    $this.data(\'selected\')? $this.stop(true,false) :
                            $this.css(\'border\',true);
});
如果您出于其他原因要遍历集合,则需要使用jQuery each()。
$(\".imagePanel\").each(function(){
    //do something
});
但是,在这种情况下,您没有必要。     ,        
$(\".imagePanel\").click(function(){
    if(!$(this).data(\'selected\')){
        $(this).css(\'border\',true);
    }else{
         $(this).stop(true,false);
    }
});
    ,        查看: http://api.jquery.com/each/     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...