简体   繁体   中英

Set css attribute in onclick event

I have a problem with set fontStyle attribute to single element(by id ) in popover. I get onClick event, put style ( bold font style) to all class elements and then try to put another style( normal ) to one(clicked) element. My code is:

$(document).on('click', '.listElement', function () {
    $('.listElement').css('font-weight', 'bold');
    alert(this.id);
    $(this).css('font-weight', 'normal');
});

There is a demo

Setting bold style for all class elements works and dialog shows correctly id so this is right element(in this ) but .css() method doesn't work. I tried to put style by using id like:

$('#A').css('font-weight', 'normal');

and there is no error in console but it doesn't work as well. Is there any other way to set fontStyle to single unique element?

Rather than removing CSS styling why not just never add it to the clicked object??

Get the ID of the clicked object and use that...

$(document).on('click', '.listElement', function () {
var clickEl = this.id; //ID of clicked object
$('.listElement').not('#' + clickEl).css('font-weight', 'bold'); //bolds everything which is NOT the clicked item.
alert(this.id);
});

or

$(document).on('click', '.listElement', function () {
$('.listElement').not('#' + this.id).css('font-weight', 'bold'); //bolds everything which is NOT the clicked item.
alert(this.id);
});

Updated Fiddle


if there is a specific reason you need to remove the styling rather than never applying it...

$(document).on('click', '.listElement', function () {
$('.listElement').css('font-weight', 'bold');
alert(this.id);
$('.listElement#' + this.id).css('font-weight', 'normal');
});

Fiddle for that

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