获取“替代”来自驻留在 内的图像的属性标签
这应该相当简单,但由于某种原因,它不起作用。
我想从标签内的图像中获取“alt”属性,
<div id="album-artwork">
<ul>
<li><a href="link to large image"><img src="thumbnail" alt="description of the image" /></a></li>
...
</ul>
</div>
$("#album-artwork a").click(function(e) {
e.preventDefault();
var src = $(this).attr("href");
var alt = $(this).next("img").attr("alt");
alert(src); // ok!
alert(alt); //output: undefined
});
有什么想法为什么 next() 不起作用?有更好的解决方案吗?
提前致谢 马可
this should be fairly simple but for some reason, it doesn't work.
I want to get the "alt" attribute from an image that resides inside an tag
<div id="album-artwork">
<ul>
<li><a href="link to large image"><img src="thumbnail" alt="description of the image" /></a></li>
...
</ul>
</div>
$("#album-artwork a").click(function(e) {
e.preventDefault();
var src = $(this).attr("href");
var alt = $(this).next("img").attr("alt");
alert(src); // ok!
alert(alt); //output: undefined
});
any ideas why next() doesn't work? Is there a better solution out there?
Thanks in advance
Marco
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
尝试使用
$(this).find('img')
来选择链接内的某个元素。Try
$(this).find('img')
instead to select some element within the link.或
测试:http://jsbin.com/amado4
or
Test : http://jsbin.com/amado4
没关系。我刚刚明白了...我意识到
img
不是的兄弟,而是
的子级代码>
这是正确的语法
Nevermind. I just got it... I've realized that the
img
is not a sibling of<a>
but a child of<a>
This is the correct syntax
.next 不会选取下一个元素(即下一个 Li 而不是 IMG)吗?
Won't .next pick up the next element which is the next Li and not the IMG?
尝试一下这个测试,它的工作原理!!!
jQuery 代码是
children()
函数查找任何子项,但如果您想查找任何特定子项,请定义子项名称,如下所示children("img")
或孩子(“按钮”)
。try this tested and its working!!!
and jQuery code is
the
children()
function find any children but if you want to find any specific children define the children name like thischildren("img")
ORchildren("button")
.不要复杂化:
Dont complicate:
这是因为图像标签位于 ul 标签内。 next 只查找同一级别的标签。您必须使用
编辑:包括缺少的附加“
It's because the image tag is inside the ul tag. next only looks for tags at the same level. You'll have to use
EDIT: included the additional " that was missing