[英]Why does this jQuery code work in Firefox but not Chrome or Safari?
I'm using jQuery to highlight (by changing bg color) some table cells. 我正在使用jQuery突出显示(通过更改bg颜色)一些表格单元格。 I want the button (a simple anchor) to be given the class name 'selected' when clicked and I want certain table cells below the buttons to highlight. 我希望按钮(一个简单的锚点)在单击时被赋予类名“选中”,我希望按钮下方的某些表格单元格突出显示。 When you click the same button again, it deselects and removes the highlights from the table cells. 再次单击同一按钮时,它将取消选择并从表格单元格中删除高光。 When you click a different button, it removes the other highlights and switches to the new appropriate ones. 单击其他按钮时,将删除其他突出显示并切换到新的相应突出显示。
This all works perfectly in Firefox. 这一切都在Firefox中完美运行。 When I try it in a webkit browser, it does not. 当我在webkit浏览器中尝试它时,它没有。 I can't figure out why and it's driving me crazy! 我无法弄清楚为什么,它让我发疯! The jQuery code is below. jQuery代码如下。 You can see the page at: 您可以在以下位置查看该页面:
http://byegurl.com/scores.html http://byegurl.com/scores.html
$(function(){
$(".press").click(function() {
id = $(this).attr("id");
name = $("." + id);
if ($(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(name).removeClass('highlight');
} else {
$('.press').removeClass('selected');
$("td:not(name)").removeClass('highlight');
$(this).addClass('selected');
$(name).addClass('highlight');
}
return false;
});
});
I appreciate your help! 我感谢您的帮助!
Change: 更改:
id = $(this).attr("id");
name = $("." + id);
to: 至:
var id = $(this).attr("id");
var name = $("." + id);
That is, declare the variables with var
so they have local scope. 也就是说,用var
声明变量,使它们具有局部范围。 Without var
, the variables had global scope and were conflicting with something. 如果没有var
,变量具有全局范围并且与某些内容相冲突。
It now works in Chrome/Safari: http://jsbin.com/efilok/ 它现在可以在Chrome / Safari中使用: http : //jsbin.com/efilok/
A few things that may solve the problem: 可以解决问题的一些事情:
name
is already a jQuery object. name
已经是一个jQuery对象。 Change this line to: 将此行更改为:
name.removeClass('highlight');
and 和
name.addClass('highlight');
Also, instead of return false;
而且,而不是return false;
, I recommend event.preventDefault()
, like this: ,我推荐event.preventDefault()
,如下所示:
$('.press').click(function(event) {
// ...
event.preventDefault();
});
Apparently name
is being used by chrome for some other purpose. 显然,chrome正在使用name
来实现其他目的。 If you were to have your name
variable not a global variable, ie. 如果你的name
变量不是全局变量,即。 var name
instead of just name
then it would probably work. var name
而不仅仅是name
然后它可能会工作。 Though I would just use a different variable name. 虽然我只想使用不同的变量名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.