我怀疑我怎么能迭代到一组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清除风格
不想要这个
答案 0 :(得分:6)
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, true).data('selected', false) :
$this.css('border', '2px solid black').data('selected', true);
});
如果您想因其他原因迭代该集合,那么jQuery each()将是您需要的。
$(".imagePanel").each(function(){
//do something
});
然而,在这种情况下,你没有必要。
答案 1 :(得分:1)
$(".imagePanel").click(function(){
if(!$(this).data('selected')){
$(this).css('border', '2px solid black').data('selected', true);
}else{
$(this).stop(true, true).data('selected', false);
}
});
答案 2 :(得分:1)
要回答更新的问题(请参阅问题评论帖子),您不需要遍历所有div。
将函数绑定到click
,将所需的css类添加到$(this)
(单击的元素)。
确保只选择一个项目的一种方法是保留当前所选元素的缓存,并在单击其他内容时从中删除关联的类。
示例:
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;
}
});
答案 3 :(得分:0)