从位于标记内的图像中获取“alt”属性
这应该是相当简单的,但由于某种原因,它不起作用。
我想从驻留在标签内的图像中获取“alt”属性
$("#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()不起作用? 那里有更好的解决方案吗?
在此先感谢Marco
这是因为图像标签位于ul标签内。 next只查找同一级别的标签。 你必须使用
var alt = $(this).children("img").attr("alt");
编辑:包括额外的“缺少
$(this).find('img').attr('alt');
尝试使用$(this).find('img')
来选择链接中的某个元素。
要么
$('img', this).attr('alt');
测试: http : //jsbin.com/amado4
不会.next拿下下一个元素,这是下一个李而不是IMG?
尝试这个测试和它的工作!
和jQuery代码是
$(document).ready(function() { $("#album-artwork a").click(function(e) { e.preventDefault(); var src = $(this).attr("href"); //var alt = $(this).next("img").attr("alt"); var alt = $(this).children().attr("alt"); //find function also do the same thing if you want to use. /*var alt = $(this).find("img").attr("alt");*/ alert(src); // ok! console.log(src); // ok! alert(alt); //output: not undefined now its ok! console.log(alt); //output: not undefined now its ok! }); });
children()
函数可以找到任何子项,但如果要查找任何特定的子项,则定义子项名称,如children("img")
或 children("button")
。