在onclick事件中设置css属性

bar*_*rmi 5 html javascript css jquery

我在弹出窗口中将set fontStyle属性设置为单个元素(by id)有问题.我得到onClick事件,将样式(bold字体样式)放到所有类元素,然后尝试将另一个样式(normal)放到一个(单击)元素.我的代码是:

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

有一个演示

设置bold所有类元素的样式工作和对话框正确显示id所以这是正确的元素(in this)但.css()方法不起作用.我尝试使用idlike 来设置样式:

$('#A').css('font-weight', 'normal');
Run Code Online (Sandbox Code Playgroud)

并且控制台中没有错误但它也不起作用.有没有其他方法将fontStyle设置为单个唯一元素?

Sco*_*ott 2

与其删除 CSS 样式,为什么不将其添加到单击的对象中?

获取单击对象的 ID 并使用它...

$(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);
});
Run Code Online (Sandbox Code Playgroud)

或者

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

更新了小提琴


如果有特定原因您需要删除样式而不是从不应用它......

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

小提琴为此