简体   繁体   中英

How to set css to more selectors when one of it is $(this)?

I want to set background color using jquery for 2 selectors:

$('#selector1, #selector2').css('background-color', '#dcf0ff');

This is working, but how to do it, when one of selector is $(this) ?

function() {
   $(this, '#element2').css('background-color', '#dcf0ff');
}

This is not working for none of selectors, and no errors are shown in the console.

You can simply use two statements:

$('#element2').css('background-color', '#dcf0ff');
$(this).css('background-color', '#dcf0ff');

Or, if the CSS is long and you don't want two, repetitive statements, add its id (supposing it has one).

$("#element2, #" + this.attr("id")).css('background-color', '#dcf0ff');

您可以通过jQuery的.add()方法将元素添加到选择器:

$(this).add('#element2').css('background-color', '#dcf0ff')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM