动态添加/删除类 Jquery
我正在创建一个自动建议框,其中返回了建议,并且我正在尝试向各个链接添加/删除“searchsuggestinnerulhighlight”类。这是动态返回的 ta
<DIV id="searchsuggestinner">
<UL id=searchsuggestinnerul>
<LI>
<A href="#" id="1" class = "hoverme" onMouseDown="searchsuggestSubmit('appalachian trail');">appalachian trail</A>
</LI>
</UL>
</DIV>
这是我的 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");
}
});
最初我有 .css("background-color"... 现在我将其更改为添加类和删除类,但它不起作用。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更改:
至:
Change:
To:
这是非常狡猾的 jQuery!
首先,您不需要
attr
来获取id
。您可以通过this.id
获取它。这要快得多。其次,您不需要获取
id
来获取包含单击元素的 jQuery 选择。只需使用$(this)
即可。最后,正如 Gabe 所说,使用
addClass
而不是add< /代码>。所以,总而言之:
但还有一件事——在 HTML5 之前的 HTML 中不允许使用以数字开头的 ID 值。其行为不受保证。
That's seriously dodgy jQuery!
First, you don't need
attr
to get theid
. You can get it withthis.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 thanadd
. So, all in all:One other thing, though -- using a ID value starting with a number was not allowed in HTML before HTML5. Its behaviour is not guaranteed.
我想把这个放在评论中,但我不能。实现 lonesomeday 的更改,但是当他使用 $(this).id 时,尝试仅使用 this.id,因为“this”应该已经是一个 jquery 对象。 (我们不需要 $($(this))。)
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)).)