我有一个类似的布局:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器在单击时选择div中的子img。
为了得到div,我有一个选择器:
$(this)
如何使用选择器获取子img?
我有一个类似的布局:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器在单击时选择div中的子img。
为了得到div,我有一个选择器:
$(this)
如何使用选择器获取子img?
当前回答
尝试以下代码:
$(this).children()[0]
其他回答
在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).children()[0]
这里有一个函数代码,您可以运行它(这是一个简单的演示)。
当您单击DIV时,您可以从一些不同的方法获得图像,在这种情况下,“this”就是DIV。
$(文档).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>
希望它有帮助!
不知道DIV的ID,我想您可以这样选择IMG:
$("#"+$(this).attr("id")+" img:first")
jQuery的每个都是一个选项:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});