简体   繁体   English

使用$(this)将子img放入div中; [点击事件]

[英]Getting the child img inside a div using $(this); [on click event]

I'm trying to get the child image of a clicked div. 我正在尝试获得单击的div的子图像。 I want to get it's src value. 我想得到它的src值。 But it's returning undefined. 但是它返回的是不确定的。 Could someone point me in the right direction? 有人可以指出我正确的方向吗?

Tried using Jquery .find() https://api.jquery.com/find/ Tried using Jquery .children() https://api.jquery.com/children/ 尝试使用Jquery .find() https://api.jquery.com/find/尝试使用Jquery .children() https://api.jquery.com/children/

Both return undefined. 两者都返回未定义。

for (let i = 0; i < $('#draw-raster > div').length; i++) {
    $(document).on('click', '#raster-item'+i, () => {
        let image = $(this).children('img').attr('src'); //undefined
        let image2 = $(this).find('img').attr('src'); //undefined


        if (image) {
            console.log(image);
            return alert("image child found!");
        }

        return setTimeout(() => {
            $('#raster-item'+i).children('img').hide();
        }, 4500);
    });
    $('#image'+i).hide();
}

load html: 加载html:

   for(let i = 0; i < 16;  i++)
    {
        let image = displayImages();

        $('#draw-raster').prepend(
            "<div id=raster-item" + i + " class='imageh"+i+"' data-id=" + i + "><img src='"+ displayImages() +"' class='image "+i+"' id='image"+ i +"' alt='Failed to load image' width='173.19' height='107.3'></div>"
        );
    }

html page: html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Memory</title>
    <script src="inc/js/jquery.min.js"></script>
    <link rel="stylesheet" href="inc/css/boostrap.min.css">
    <link rel="stylesheet" href="inc/css/memory.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>

<div class="container justify-content-center">
    <div class="wrapper">
      <div class="row">
          <div class="col-lg-9">
              <div class="card">
                  <div class="card-header bg-dark" style="color:white;">
                      <h2>Memory</h2>
                  </div>
                  <div class="card-body">
                      <section class="col-12 mx-auto" id="draw-raster">

                      </section>
                  </div>
              </div>
          </div>
          <div class="col-lg-3">
              <div class="card">
                  <div class="card-header bg-dark" style="color:white;">
                      <h2>Turns</h2>
                  </div>
                  <div class="card-body">
                      <div id="turns">Turns: 0</div>
                      <div id="sets">Sets: 0</div>
                  </div>
              </div>
              <div class="form-group">
                <button class="btn btn-success col-12" type="button" id="reset">Reset scores</button>
            </div>
          </div>
      </div>
    </div>
</div>

<script src="inc/js/memory.js"></script>

</body>
</html>

Both attempts return undefined, i'm uncertain what would work. 两种尝试均返回未定义的值,我不确定哪种方法有效。 Yes, I've been spamming google too. 是的,我也一直在向Google发送垃圾邮件。 :'^) :'^)

A couple of notes on your code: 关于代码的一些注意事项:

1) If you want to use this you'll need to switch from an arrow function back to a regular anonymous function. 1)如果要使用this功能,则需要从箭头功能切换回常规的匿名功能。 Arrow functions don't have a this of their own and will borrow the context from their outer lexical environment. Arrow函数本身没有this ,它将从其外部词法环境中借用上下文。 It's why your code keeps return undefined. 这就是为什么您的代码保持返回未定义的原因。

2) You don't need a loop. 2)您不需要循环。 The benefit of using jQuery is that you can operate on collections of elements all at once. 使用jQuery的好处是您可以一次处理所有元素的集合。 In your case you're attaching a single event listener to a parent element (here: document ) and waiting for events to bubble up from the .raster-item img s and be "captured". 在您的情况下,您要将单个事件侦听器附加到父元素(此处为document ),并等待事件从.raster-item img并被“捕获”。 This is called event delegation and is useful when you want to process new elements added to the DOM after it has loaded. 这称为事件委托 ,当您要在DOM加载后要处理添加到DOM的新元素时,此方法很有用。

2) You will find it easier to use a class instead of many ids. 2)您会发现使用类而不是许多ID会更容易。

Here's an example based on your code with these changes: 这是一个基于您的代码的示例,其中包含以下更改:

 // Use event delegation to add an event listener to the element with // the container class that watches out for click events on **all** // elements with the raster-item class that contain images $('.container').on('click', '.raster-item img', function () { // `$(this)` will be the image element, so simply grab its src // from the attribute console.log($(this).attr('src')); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="raster-item"><img src="https://dummyimage.com/50x50/555/fff.png" /></div> <div class="raster-item"><img src="https://dummyimage.com/50x50/777/fff.png" /></div> <div class="raster-item"><img src="https://dummyimage.com/50x50/999/fff.png"/></div> <div class="raster-item"><img src="https://dummyimage.com/50x50/bbb/fff.png" /></div> </div> 

You don't need jQuery for this. 您不需要jQuery。 You can harness the power of event bubbling with vanilla JavaScript. 您可以利用原始JavaScript利用事件冒泡的功能

In the web page below, the code inside the script tags, listen for a click event and runs some code if that event happens, ie bubbles, through a DIV element: 在下面的网页中, script标签内的代码侦听click事件,并在事件发生时通过DIV元素运行一些代码(例如气泡):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Clicked div img</title>
</head>
<body>
  <div class="catcher">
    <p>This is a div with an image inside</p>
    <img src="image-to-pick.jpg" alt="image to pick" ()>
  </div>

  <script>
    document.addEventListener('click', function (event) {
      if (event.target.tagName == 'DIV') {
        var imgToPick = event.target.querySelector('img');
        console.log(imgToPick.src); // add your code here
      } 
    }, false);
  </script>
</body>
</html>

In other words, you trigger a "click event" whenever you click on that page, that event bubbles up until it reaches the root of the HTML document (which you can imagine as an upside-down tree where the root is the html tag). 换句话说,每当您单击该页面时,都会触发一个“单击事件”,该事件冒泡直到到达HTML文档的根(您可以将其想象为一个倒置的树,其中根是html标记) 。 If you don't need or don't want to let it bubble to the elements "above" you DIV, you can also stop the propagation of that click event by using event.stopPropagation() , right after you handle the img src. 如果您不需要或不想让它冒泡到DIV上方的元素,则还可以在处理img src之后立即使用event.stopPropagation()停止该click事件的传播。

You can find more info about how this works here on MDN (Mozilla Dev. Network) 您可以在MDN(Mozilla Dev。Network)上找到有关此工作原理的更多信息

I'm not quite sure in what context you need to do this, but with jquery it's pretty straight forward. 我不太确定您需要在什么情况下执行此操作,但是使用jquery会非常简单。

If you have multiple images within a parent div, you can set the child images as the selecters for the click event, and return each image src when clicked on directly. 如果父div中有多个图像,则可以将子图像设置为click事件的选择器,并在直接单击时返回每个图像src。

The resulting jquery is only three lines long this way, and you can add as many images as you like to the parent div: 这样生成的jquery只有三行,您可以向父div添加任意数量的图像:

<div class="image-container">
  <img id="first" src="first-source-goes-here.jpg" alt="img text" />
  <img id="second" src="second-source-goes-here.jpg" alt="img text" />
  <img id="third" src="third-source-goes-here.jpg" alt="img text" />
</div>


$(".image-container > img").click(function() {
  // replace 'alert' with what ever you need it to be
  alert( $(this).attr("src") )
})

EDIT: 编辑:

In response to Andy's comment on my answer below, if you are loading images once the DOM has been loaded, then you could run a check on the click parent div to see if there are any images within it before returning the source: 为了回应Andy对下面我的回答的评论,如果您在DOM加载后立即加载图像,则可以在单击父div上进行检查,以查看其中是否包含任何图像,然后再返回源:

$(".image-container").click(function() {
    if( $(this).children("img").length > 0 ) {
    alert( $(this).find("img").attr("src") )
  }  else {
    alert('there are no images here')
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM