【发布时间】:2014-10-22 22:39:12
【问题描述】:
我需要为一些元素附加 onclick 事件。这些点击事件需要对应以下元素。
例如:(jsfiddle here)
HTML:
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
<br/>
<br/>
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
<br/>
<br/>
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
CSS:
.divs{
background:lightblue;
width:50px;
height:50px;
margin:10px;
}
span{
background:pink;
margin:10px;
padding:10px;
}
JQUERY:
$(function(){
divs = $('.divs');
divs.each(function(){
$this = $(this);
s1 = $this.closest('span').find('.s1');
s2 = $this.closest('span').find('.s2');
s1.click(function(){
alert('S1 click');
$this.css('background', 'green');
});
s2.click(function(){
alert('S2 click');
$this.css('background', 'blue');
});
});
});
我想点击任意一个 span 元素并对下面的 div 执行操作。
【问题讨论】:
-
.next接受选择器作为参数。您需要使用$this.next('div.divs')。 -
@SergiuParaschiv 只过滤下一个跟随元素,需要使用
.nextAll('.divs:first') -
对了,忘记了。
-
你能用 jsfiddle 演示吗?我不太明白这将如何工作,谢谢:)
标签: jquery html css jquery-selectors onclick