gpt4 book ai didi

jquery 更改具有相同类的不同 id 的 css

转载 作者:行者123 更新时间:2023-11-28 18:52:41 25 4
gpt4 key购买 nike

我有 3 个相同类别的 div。

<div id="qq1" class="cl">sentence</div>
<div id="qq2" class="cl">sentence</div>
<div id="qq3" class="cl">sentence</div>

好吧,我想知道如何编写正确的代码来使用一个函数调用 3 个 div(调用 cl 类)并返回正确的 id 以更改 css.for ex:

<script>
$('.cl').live('mouseenter', function() {
var currentId = $(this).attr('id');
$('currentId').css("background-color", "#99cc33");
$('currentId').css("color", "white");
});
$('.cl').live('mouseleave', function() {
var currentId = $(this).attr('id');
$('currentId').css("background-color", "white");
$('currentId').css("color", "#404040");
});
</script>

但是有一些问题,因为它不起作用

最佳答案

您永远不会使用 currentId 变量,而是尝试使用包含字母 c、u、r 等的字符串,'currentId' .

要使其与该变量一起使用,您需要说 $('#' + currentId).css() - 因此,例如,currentId'qq1' 那么实际上你会说 $('#qq1').css()

但是你根本不需要 id 因为你可以简单地使用 $(this):

$('.cl').live('mouseenter', function() {
$(this).css({"background-color" : "#99cc33",
"color" : "white"});
});

$('.cl').live('mouseleave', function() {
$(this).css("background-color", "white");
$(this).css("color", "#404040");
});

在 jQuery 事件处理程序中,this 引用 DOM 元素本身,而 $(this) 为该元素创建一个 jQuery 对象,以便您可以调用 jQuery 方法它。请注意 .css() method接受多个属性的映射,因此您可以通过一次调用来设置所有属性 - 我已经在 mouseenter 而非 mouseleave 中展示了该语法,以便您进行比较。

(注意:与您的问题完全无关,但如果您使用的是 jQuery 1.7+,则应停止使用 .live(),因为它已被弃用,取而代之的是 .on() - .live() doco page 上有说明如何转换代码。如果您使用的是 < 1.7 但 > 1.4.2,则应使用 .delegate()。)

关于jquery 更改具有相同类的不同 id 的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858987/

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