如何使用jQuery将以前捕获的变量传递给后台属性?我正在使用一个非常大的表,很多单元格和大量数据。使用了多种颜色,应用于表而不是单元格(有充分的理由)。
这是我的代码(非常精简的HTML)
<table>
<tr>
<td class="nonLevel"><ul class="list"><li>text to go here</li></ul></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
</tr>
</table>
$(".block").hover(function () {
var myColor = $(this).css("background-color");
$(this).css({'background-color' : 'yellow'});
}, function () {
var cssObj = {
'background-color' : myColor,
}
$(this).css(cssObj);
});
所以我试图在翻转时捕获原始颜色(当我将myColor
变量传递给警报时起作用),然后将颜色更改为黄色,然后在rollout切换回“myColor”。
我查看了addClasss
和removeClass
,但他们似乎并没有根据设置方式来削减它。同样,背景颜色在表格中的CSS中设置,而不是单元格,这不能更改。
答案 0 :(得分:3)
您还可以使用jQuery数据来存储原始颜色。然后在mouseout上获取它。
$(".block").each(function (index, elem) {
$(elem).data('orginalColor', $(elem).css("background-color"))
}).hover(function () {
$(this).css({'background-color' : 'yellow'});
}, function () {
$(this).css({'background-color' : $(this).data('orginalColor')});
});
您可以在此处阅读jQuery数据:jQuery Data
另外我建议使用委托(jQuery在某些情况下会在内部使用它)。这只绑定了整个表的一个事件处理程序,而不是每个'td'
的一个事件处理程序$('.block').each(function (index, elem) { //code });
$('table').delegate('td', 'mouseover', function() { //code });
$('table').delegate('td', 'mouseout', function() { //code });
..弗雷德里克
答案 1 :(得分:2)
您不需要存储背景颜色 - 甚至不需要使用JavaScript / jQuery。你只需使用CSS:
.block:hover {
background-color: yellow;
}
如果你必须使用JavaScript(例如,因为你需要支持IE6),只需将background-color设置为空:
$(".block").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "");
});
如果您仍然认为需要存储颜色,请使用jQuerys数据功能:
$(".block").hover(function() {
$(this).data("background-color", $(this).css("background-color"));
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", $(this).data("background-color"));
});
答案 2 :(得分:1)
您可以将现有颜色填充到数据属性中:
$(".block").hover(function () {
$(this).data("bkg",$(this).css("background-color"));
$(this).css('background-color', 'yellow');
}, function () {
$(this).css("background-color", $(this).data("bkg"));
});
答案 3 :(得分:1)
$('.block').live('mouseover mouseout', function(event) {
var $this = $(this);
if (event.type === 'mouseover') {
var myColor = $this.css('background-color');
$this.data('myColor', myColor);
$this.css('background-color': 'yellow');
} else {
$this.css('background-color', $this.data('myColor'));
}
});
答案 4 :(得分:0)
我相信你必须在jQuery调用之外声明你的myColor变量。否则它应该是一个局部变量,这意味着它会在handlerOut上第二次调用hover之前超出范围。