gpt4 book ai didi

javascript - 在 onclick 事件中设置 css 属性

转载 作者:太空狗 更新时间:2023-10-29 16:34:34 24 4
gpt4 key购买 nike

我在将弹出窗口中的 fontStyle 属性设置为单个元素(通过 id)时遇到问题。我收到 onClick 事件,将样式(bold 字体样式)添加到所有类元素,然后尝试将另一种样式(normal)添加到一个(单击)元素。我的代码是:

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

有一个demo

为所有类元素设置 bold 样式有效,对话框正确显示 id 所以这是正确的元素(在 this 中)但是 .css() 方法不起作用。我尝试使用 id 放置样式,例如:

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

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

最佳答案

与其删除 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);
});

$(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


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

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

Fiddle for that

关于javascript - 在 onclick 事件中设置 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43440733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com