从父母属性设置属性
我有这个 HTML,我正在尝试将 href 从 photo.php 转换为 #photo 等,对于每个
<ul id="menu">
<li id="home" class="tab_selected"><a href="home.php">Home</a></li>
<li id="portfolio"><a href="portfolio.php">Portfolio</a></li>
<li id="music"><a href="music.php">Music</a></li>
<li id="video"><a href="video.php">Video</a></li>
<li id="photo"><a href="photo.php">Photo</a></li>
</ul>
我一直在尝试这样的事情:
$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));
但 href 总是显示为未定义。
我将哈希值存储在 li#id 中,但如果我不能这样做,那就更好了。
谢谢。
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each
<ul id="menu">
<li id="home" class="tab_selected"><a href="home.php">Home</a></li>
<li id="portfolio"><a href="portfolio.php">Portfolio</a></li>
<li id="music"><a href="music.php">Music</a></li>
<li id="video"><a href="video.php">Video</a></li>
<li id="photo"><a href="photo.php">Photo</a></li>
</ul>
I have been trying something like this:
$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));
But the href always comes out undefined.
I am storing the hash in the li#id but if i could not do this it would be even better.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$(this)
并不引用您认为它引用的对象。通过
.attr
,您可以使用函数作为第二个参数来计算每个匹配元素的新属性值,如下所示:在上面的示例中,
this
引用正确的上下文(当前迭代的锚元素)。您可以在这里尝试。
$(this)
does not refer to the object you think it refers to.With
.attr
you can use a function as a second argument to compute new attribute values for each matched element, like this:In the above example,
this
refers to the correct context (the currently iterated anchor element).You can try it here.
全部 jQuery
部分 jQuery
少部分 jQuery
任君选择:)
All jQuery
Part jQuery
Less Part jQuery
Take your pick :)
问题是
this
不包含错误的值(它指的是可能存在的任何包装上下文),因为您不在正确的上下文中。查看(当前)另外 3 个答案中的任何一个,了解如何解决此问题(提示,您想使用每个)The problem is that
this
doesnt holds the wrong value (it refers to any wrapping context there may be), because you're not in the proper context. Look at either of the (currently) 3 other answers to see how to get around this issue (hint, you want to use each)