我有一个类似的布局:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器在单击时选择div中的子img。
为了得到div,我有一个选择器:
$(this)
如何使用选择器获取子img?
我有一个类似的布局:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器在单击时选择div中的子img。
为了得到div,我有一个选择器:
$(this)
如何使用选择器获取子img?
当前回答
在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
其他回答
在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
如果DIV标记后面紧跟IMG标记,则还可以使用:
$(this).next();
您可以使用以下任一方法:
1 find():
$(this).find('img');
2个孩子():
$(this).children('img');
您也可以使用
$(this).find('img');
这将返回作为div后代的所有img
如果您的img正好是div中的第一个元素,请尝试
$(this.firstChild);
$(“#box”).click(函数){让img=$(this.firstChild);console.log({img});})<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“box”><img src=“https://picsum.photos/seed/picsum/300/150“></div>