开发者

Why does this jQuery code work in Firefox but not Chrome or Safari?

开发者 https://www.devze.com 2023-04-11 13:09 出处:网络
I\'m using jQuery to highlight (by changing bg color) some table cells. I want the button (a simple anchor) to be given the class name \'selected\' when clicked and I want certain table cells below th

I'm using jQuery to highlight (by changing bg color) some table cells. 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 ne开发者_运维百科w appropriate ones.

This all works perfectly in Firefox. When I try it in a webkit browser, it does not. I can't figure out why and it's driving me crazy! The jQuery code is below. You can see the page at:

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. Without var, the variables had global scope and were conflicting with something.

It now works in Chrome/Safari: http://jsbin.com/efilok/


A few things that may solve the problem:

name is already a jQuery object. Change this line to:

name.removeClass('highlight');

and

name.addClass('highlight');

Also, instead of return false;, I recommend event.preventDefault(), like this:

$('.press').click(function(event) {
    // ...
    event.preventDefault();
});


Apparently name is being used by chrome for some other purpose. If you were to have your name variable not a global variable, ie. var name instead of just name then it would probably work. Though I would just use a different variable name.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号