我需要为许多元素附加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执行操作。
答案 0 :(得分:1)
试试这个:
<div class="wrapper">
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
</div>
<br/>
<br/>
<div class="wrapper">
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
</div>
<br/>
<br/>
<div class="wrapper">
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
</div>
jQuery部分:
$(function(){
$('span.s1').on('click', function () {
$(this).parent().find('.divs').css('background', 'green');
});
$('span.s2').on('click', function () {
$(this).parent().find('.divs').css('background', 'blue');
});
});
答案 1 :(得分:0)
我认为你不需要在每个函数中包装你的事件监听器。 我很确定这会起作用(并减少代码量):
$(function(){
$('.s1').click(function() {
alert('s1 clicked');
// If you want to change all of the .divs
$(this).siblings('.divs').css('background', 'green');
// If you just want to change the first .divs
$(this).next().next().css('background', 'green');
});
$('.s2').click(function() {
alert('s2 clicked');
// If you want to change all of the .divs
$(this).siblings('.divs').css('background', 'blue');
// If you just want to change the first .divs
$(this).next().next().css('background', 'blue');
});
});