addClass() 没有添加类
I am using jQuery for the first time to add a class to an element within the navigation bar, but the class, '.selected' isn't being added.
Please can you tell me where I am going wrong?
Here is an example: http://jsfiddle.net/v32qy/2/
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
this
不是一个 jQuery 对象,它是实际的 DOM 元素。要将其转换为 jQuery 对象,请使用$(this)
。所以:jsFiddle 中的另一个问题是您没有选择
元素,而是选择
。最后,该链接已被跟踪。 这里已经解决了所有问题。
您可能会考虑的其他事情是
element.innerText<据我所知,/code> 没有很好的浏览器支持(即它只适用于 IE)。只是一个小注意点。
this
is not a jQuery object, it's the actual DOM element. To turn it into a jQuery object, use$(this)
. So:Another problem in the jsFiddle is that you're not selecting the
<a>
element, you're selecting the<h2>
. Finally, the link is being followed. Here's all that fixed.Something else you might consider is that
element.innerText
doesn't have very good browser support from what I've seen (i.e. it only works in IE). Just a small point of note.除了更正语法之外,您还希望将类应用于锚点。
You want apply the class to the anchor, in addition to correcting the syntax.
要访问当前元素,您必须使用
$(this)
而不仅仅是this
这是更新的小提琴。
http://jsfiddle.net/v32qy/6/
我还改变了您获取使用 jQuery
text()
函数的内部文本To access the current element you have to use
$(this)
and not justthis
Here is the updated fiddle.
http://jsfiddle.net/v32qy/6/
I have also changed the way you are getting the inner text to use jQuery
text()
function