![](/img/trans.png)
[英]Fire click event on one element in a set of matched elements and not on matched elements
[英]jQuery, Add elements to the set of matched element using string and variable
我有一个click事件,我想将一个类添加到所单击的当前元素中,再加上一个其他元素,我想一行完成该操作。
我已经尝试过类似的东西
JS文件
$('div').click(function(){
$(this, 'span').css('background','yellow');
// could usethe following way but it's not DRY
// $(this).css('background','yellow');
// $('span').css('background','yellow');
});
HTML文件
<div>
div
</div>
<span>
span
</span>
这是个小提琴
但这是行不通的,所以我不用重复css
方法怎么办。
您可以使用.add(selector)
方法,如下所示:
$(this).add('span').css('background','yellow');
您可以将<span>
元素添加到$(this)
jQuery实例中:
$(this).add( $('span') ).css('background', 'yellow');
甚至:
$(this).add('span').css('background', 'yellow');
尝试同级 ():
$('div').click(function(){
$(this).siblings('span').css('background','yellow');
})
示例: http : //jsfiddle.net/Hhqc8/6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.