[英]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.