我想在$(this)选择器中"选择"一个img.我知道我可以通过使用找到它,.find('img')
但这是可能的:
$("img",this)
?
什么是最佳的方法?
最初是代码
<a class="picture" href="test.html">
<img src="picture.jpg" alt="awesome">
</a>
Run Code Online (Sandbox Code Playgroud)
And*_*ong 68
什么是最佳的方法?
这两个$(this).find('img')
和$('img', this)
是等价的.
来自文档:
在内部,选择器上下文是使用.find()方法实现的,因此$('span',this)等价于$(this).find('span').
这是一种完美的合理方式。
因此,您想要:
$('a').click( function() {
//if the element dosent change you can use this
//var src = $('img', this).attr('src');
//else use $(this)
var src = $('img', $(this)).attr('src');
alert(src);
return false;
});
Run Code Online (Sandbox Code Playgroud)
请参阅:http://jsfiddle.net/xYmwV/
实际上没有什么区别,因为在这两种方法中,您都加载dom元素并进行搜索。您的做法是“更简洁”,更简单,但可能会更加混乱:)
一种更快的方法是,$(this).children()
因为它随后不必搜索元素,而是直接在DOM中降级。但是它消除了脚本的灵活性。