我有一个类似的布局:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器在单击时选择div中的子img。
为了得到div,我有一个选择器:
$(this)
如何使用选择器获取子img?
我有一个类似的布局:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器在单击时选择div中的子img。
为了得到div,我有一个选择器:
$(this)
如何使用选择器获取子img?
当前回答
直接子女是
$('> .child-class', this)
其他回答
在jQuery中引用子级的方法。我在下面的jQuery中总结了它:
$(this).find("img"); // any img tag child or grandchild etc...
$(this).children("img"); //any img tag child that is direct descendant
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag child that is direct descendant
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
您也可以使用
$(this).find('img');
这将返回作为div后代的所有img
使用本机javascript,您可以使用
如果您有多个图像标记,请使用
this.querySelectorAll(“img”)
如果只有一个图像标签,那么我们
this.querySelector(“img”)
你可以使用
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>
$(文档).ready(函数){//当你点击DIV时,你用“this”$('#my_div').click(function(){console.info('初始化测试..');console.log('方法#1:'+$(this).childres('img'));console.log('Method#2:'+$(this).find('img'));//这里,我选择了<IMG>的第一个出现console.log('Method#3:'+$(this).find('img:eq(0)'));});});.目录{背景色:黄色;宽度:100%;高度:200px;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“my_div”class=“the_div”><img src=“…”></div>