简体   繁体   中英

Dynamic Add/Remove Class Jquery

I am creating an autosuggest box that has a of suggestion returned to it, and I am trying to add/remove the class "searchsuggestinnerulhighlight" to individual links. Here is the dynamically returned ta

    <DIV id="searchsuggestinner">
    <UL id=searchsuggestinnerul>
    <LI>
    <A href="#" id="1" class = "hoverme" onMouseDown="searchsuggestSubmit('appalachian trail');">appalachian trail</A>
   </LI>
   </UL>
   </DIV>

And here is my jQuery:

 $(".hoverme").live("mouseover mouseout", function(event) {
    if ( event.type == "mouseover" ) {
       $("#" + mocount).removeClass("searchsuggestinnerulhighlight");
       mocount = $(this).attr('id');
       $("#" + mocount).addClass("searchsuggestinnerulhighlight");
    } else {
       $("#" + mocount).removeClass("searchsuggestinnerulhighlight");
    }
 });

Originally I had .css("background-color"... and now I've changed it to add class and remove class and it does not work. Any ideas?

Change:

$("#" + mocount).add("searchsuggestinnerulhighlight");

To:

$("#" + mocount).addClass("searchsuggestinnerulhighlight");
mocount = $(this).attr('id');
$("#" + mocount)

That's seriously dodgy jQuery!

First, you don't need attr to get the id . You can get it with this.id . This is far, far quicker.

Second, you don't need to get the id to get a jQuery selection containing the clicked element. Just use $(this) instead.

Finally, as Gabe has said, use addClass rather than add . So, all in all:

$(this).addClass('searchsuggestinnerulhighlight');

One other thing, though -- using a ID value starting with a number was not allowed in HTML before HTML5. Its behaviour is not guaranteed.

I would put this in a comment, but I can't. Implement lonesomeday's changes, but when he uses $(this).id, try just using this.id as 'this' should already be a jquery object. (We don't want $($(this)).)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM