gpt4 book ai didi

jquery - 在表格、li、ul 和 div 中选择一个 来改变背景颜色

转载 作者:太空宇宙 更新时间:2023-11-04 16:22:37 25 4
gpt4 key购买 nike

我正在尝试访问以下 td 'dayContent' 并将背景颜色更改为 #a43802。我尝试了几种方法都没有成功。

这个 td 存在于一个 tr 和 table 中,它被一个 div、一个 li、一个 ul 然后另一个 div 包围。 :(

dayContent 的内容是从我的后端代码生成的。目前,如果您将鼠标悬停在列上,标题背景会更改颜色,这是正确的行为。

但是,我无法选择“个别”.dayContent 元素来更改背景颜色,而是更改列中的所有 .dayContent 背景颜色。

所需的效果是更改列标题的背景颜色,并且鼠标悬停在当前 .dayContent 上的背景颜色也应更改。我试过访问 <p>但它做同样的事情并将背景颜色更改为所有 <p>在专栏中。

Soo....任何人都可以指出我正确的方向吗?我的脑袋疼。

JQUERY 代码:

        $('#columnDay1').css('cursor', 'pointer');
$('#columnDay1').mouseover(function () {
$('td.calendarHeader', this).css("background-color", "#a43802");
});
$('#columnDay1').mouseout(function () {
$('td.calendarHeader', this).css("background-color", "#37322e");
});
$('#testSpot').mouseover(function () {
$('td.dayContent', this).css("background-color", "#a43802");
});
$('#testSpot').mouseout(function () {
$('td.dayContent', this).css("background-color", "White");
});

HTML 代码:

    <tr>
<td class='dayContentImage' height='174' Width='187' BACKGROUND='/Images/day1_10am.jpg'><p><span class='dayContentImageDay'>10</span>AM</p></td>
</tr>
<tr>
<td class='dayContent'><p id='testSpot'><span class='dayContentDay'>6</span>PM<br />Content</p></td>
</tr>
<tr>
<td class='dayContent'><p id='testSpot'><span class='dayContentDay'>6</span>PM<br />Content</p></td>
</tr>
<tr>
<td class='dayContentImage' height='173' Width='187' BACKGROUND='/Images/day1_7pm.jpg'><p><span class='dayContentImageDay'>7</span>PM</p></td>
</tr>
<tr>
<td class='dayContent'><p id='testSpot'><span class='dayContentDay'>9</span>PM<br />Content</p></td>
</tr>

谢谢。

最佳答案

让我们从定义您的代码中遇到的一些问题开始。

1) DOM 元素必须有唯一的 ID。您在这里使用了几次#testSpot,这很糟糕,会使您的代码表现得很奇怪。

2) 执行此操作时:$('td.dayContent', this).css("background-color", "#a43802");您正在寻找 <td>dayContent , this 的上下文中对象!this在这种情况下是你的 #testSpot ,其中不包含 <td>有一个名为 dayContent 的类.

一个解决方案是(在修复重复 ID 的使用后 - 仅恢复到类并且不基于 ID!)在鼠标悬停事件中使用类似这样的东西: $(this).parent("td.dayContent").css("background-color", "#a43802"); .

但是,这是一个糟糕的解决方法,可以使用基本的 jQuery 和 CSS 类来实现这种效果。你可以做的,也是最好的做法是添加一个名为 hover 的类。当鼠标悬停在元素上并在鼠标移出时将其删除,然后只需添加 CSS 即可更改此类元素的背景颜色。你可以这样做:

$("td.dayContent").hover(function(){ $(this).addClass("hover"); }, function(){ $(this).removeClass("hover"); });

然后您可以通过 CSS(这是设计的正确位置,而不是 JS!)设置样式,如下所示:

td.dayContent { background-color: white; } // default color
td.dayContent.hover { background-color: green; } // color when the td is being hovered.

关于jquery - 在表格、li、ul 和 div 中选择一个 <td> 来改变背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290420/

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