简体   繁体   中英

jQuery on click not firing

I know this question has been asked thousands of times, but I can't seem to figure out my issue. I just need another set of eyes on it to see what I'm doing wrong or what I'm missing.

Here is my code:

<div class="image-container">
  @foreach (var image in Model)
  {
    <a href="#" class="returnImage" data-url="@Request.Url.GetLeftPart(UriPartial.Authority)@image.Url">
      <img src="@image.Url" id="UploadImage" data-source="@image.Url" width="200" height="200">
    </a>
  }
</div> 

<script>
  $(document).ready(function () {
    $("div.image-container").on("click", ".returnImage", function(e) {
      var urlImage = $(this).attr("data-url");
      window.opener.updateValue("cke_72_textInput", urlImage);
      window.close();
    });
  });
</script>

Debugging with FireBug shows no errors and when I put a breakpoint on the "on click" function, it is never hit/never fires. What am I missing here?

What's probably happening is the <a> tags are taking precedence when you click on them, suppressing the click event you have for your div.image-container element.

If you are intending on having the user click on the whole container itself, try using something else besides an <a> tag for each image in the model.

If you are intending on putting a click handler on each <a> tag inside your div.image-container , your jQuery event line should look like this instead:

$("div.image-container a").click(function(e) {

Try this:

$(".returnImage").on("click", function(e) {
  //whatever action code
});

Where as nothing is firing, it may be that your pop-up blocker thinks your script is trying to hi-jack your browser and therefor is blocking it, especially since it is an <a> anchor tag wrapped in functionality that would trigger default link behavior as interpreted by the browser. The code below is yours with a .preventDefault() behavior routine added, just in case that is the issue. Edit: Updated coded to more accurately target the DOM element you want (as suggested by other answers).

preventDefault API

  $(document).ready(function () {
    $(".returnImage").on("click", function(e) {
      e.preventDefault();
      var urlImage = $(this).attr("data-url");
      window.opener.updateValue("cke_72_textInput", urlImage);
      window.close();
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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