并想用一个jQuery选择器选择子img内div的..."> 并想用一个jQuery选择器选择子img内div的..."/> 并想用一个jQuery选择器选择子img内div的..."> 并想用一个jQuery选择器选择子img内div的...">

如何获得$(this)选择器的子级?

JavaScript

GO西门

2020-03-09

我有一个与此类似的布局:

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

并想用一个jQuery选择器选择子imgdiv的点击。

要获得div,我有以下选择器:

$(this)

如何img使用选择器让孩子

第201篇《如何获得$(this)选择器的子级?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
null 2020.03.09

您的中可能有0到许多<img>标签<div>

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

为了确保代码安全,请使用.each()

在一起使用.find().each()可以防止<img>元素为0 出现空引用错误,同时还允许处理多个<img>元素。

// Set the click handler on your div
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {

  // Find the image using.find() and .each()
  $(this).find("img").each(function() {
  
        var img = this;  // "this" is, now, scoped to the image element
        
        // Do something with the image
        $(this).animate({
          width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
        }, 500);
        
  });
  
});
#mydiv {
  text-align: center;
  vertical-align: middle;
  background-color: #000000;
  cursor: pointer;
  padding: 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>

ItachiGreen 2020.03.09

这也应该工作:

$("#id img")
达蒙阿飞斯丁 2020.03.09

试试这个代码:

$(this).children()[0]
Near小哥Green 2020.03.09

我不知道DIV的ID,我认为您可以像这样选择IMG:

$("#"+$(this).attr("id")+" img:first")
Tom阳光达蒙 2020.03.09

在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
神奇宝儿 2020.03.09

如果您的DIV标签后面紧跟着IMG标签,则还可以使用:

$(this).next();
小小Eva 2020.03.09

如果您需要将第img一个水平降低一个水平,则可以执行

$(this).children("img:first")
罗静云 2020.03.09

jQuery构造函数接受名为的第二个参数context,该参数可用于覆盖选择的上下文。

jQuery("img", this);

.find()就像这样使用

jQuery(this).find("img");

如果您想要的img 是clicked元素的直接后代,则还可以使用.children()

jQuery(this).children("img");

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android