jquery addclass to the current a tag, not to all a tags inside div

I want to add an "active" class to the current link, I have the following code: The jquery: $("#products a").each(function() { if(this.href == window.location || this.href == document.location.protocol + "//" + window.location.hostname + window.location.pathname) $(this).addClass("selectedThumb"); }); The html: I want to end up with just current link that is clicked having the "selectedThumb" class added. Right now the class is being added to all the a tags and I'm ending up with this: This is a product image thumb viewer, so I'm always staying on the current page, not leaving the page after the a link is clicked, instead the product thumbnail changes on the page. That code works fine. Not sure if this could have smth to do with it. ADDITIONAL INFO The a tags that I'm trying to add the 'active' state / css class to are thumb images that when hovered have a mouseover event that display that thumb in that page, and the thumbs have no link. The mouseover event calls a JS function that displays the correct product image. The JS it calls: function displayImage(index, parent){ var images = document.getElementById(parent).getElementsByTagName("div"); for(var i = 0; i < images.length; i++) { var image = images[i]; if (image.className != 'pimage') { continue } if(i == index-1) { image.style.display="block"; } else { image.style.display="none"; } } } So because the a links don't really link anywhere, the jQuery addClass is being added to all the thumbnail links.
tags should always have a href attribute (unless you're using them as a named anchor, which isn't the case here). The browser will not render them as links (and won't apply the hover events, etc) without a href. The common approach is to set href="#"

以上就是jquery addclass to the current a tag, not to all a tags inside div的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » jQuery 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准