我有一个类似的布局:

<div id="..."><img src="..."></div>

并希望使用jQuery选择器在单击时选择div中的子img。

为了得到div,我有一个选择器:

$(this)

如何使用选择器获取子img?


当前回答

此外,这也应该起作用:

$("#id img")

其他回答

<div>中可能有0到多个<img>标记。

要查找元素,请使用.find()。

要确保代码安全,请使用.each()。

在0<img>元素的情况下,同时使用.find()和.each()可以防止空引用错误,同时还可以处理多个<img>的元素。

//在div上设置单击处理程序$(“body”).off(“click”,“#mydiv”).on(“cli”,“#mydiv”,function(){//使用.Find()和.each()查找图像$(this).find(“img”).each(function(){var img=此;//“this”现在作用于image元素//对图像执行某些操作$(this).animate({width:($(this).width()>100?100:$(this).width()+100)+“像素”}, 500);});});#mydiv公司{文本对齐:居中;垂直对齐:中间;背景色:#000000;光标:指针;填充:50px;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js“></script><div id=“mydiv”><img src=“”width=“100”height=“100”/></div>

在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

直接子女是

$('> .child-class', this)

如果您的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>

如果DIV标记后面紧跟IMG标记,则还可以使用:

$(this).next();