Kelvin
Kelvin

Reputation: 585

How can I trigger multiple selector

Do anyone has similar experience? I would like to write a code to trigger the user when clicking the image for further action. I write the jQuery code but not successful in the trigger, code as below

  $( "#tab-3-list img" ).on( "click", function(e) {
    e.preventDefault();
    windows.alert( $(this).id);
  });

Below is the HTML code

<div id="tab-3-list">
    <div class="ui-grid-a">
        <div class="ui-block-a"><div class="imgspace"><img id="c01" class="coupon_list" src="/images/coupon/c01.png"></div></div>
        <div class="ui-block-b"><div class="imgspace"><img id="c02" class="coupon_list" src="/images/coupon/c02.png"></div></div>
    </div><!-- /grid-a -->
</div><!-- /tab-3-list -->

/-------------------------------/

I finally found the problem is if I put the div#tab-3 in main body, then the browser can trigger the click on the image. But it doesn't work if the div#tab-3 is loaded from external file using script

$(document).load("list.html");

Upvotes: 0

Views: 196

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

Your selector is fine assuming you want to handle clicks on either image element, and your .on("click") binding will work assuming you include that code in a document ready handler or in a script block after the elements it tries to access. (And assuming you have included jQuery on your page before the code in question.)

However, you have two errors inside the handler function:

  1. It should be window.alert(), not windows.alert() (no "s" in "window"). Or you can just say alert() without the window.

  2. $(this) returns a jQuery object which doesn't have an id property, so $(this).id returns undefined. Just use this.id. If you want to call a jQuery method on the clicked image then you'd use $(this), for example $(this).hide().

So like this:

$(document).ready(function () {

    $("#tab-3-list img").on("click", function (e) {
        e.preventDefault();
        window.alert(this.id);
    });

});

Demo: http://jsfiddle.net/JZvvs/

Upvotes: 1

Related Questions