简体   繁体   中英

JQuery - Event do not fire for element under some other element

I am facing a situation where I want to handle click event of li that is present under another element with class optWrapper . Most of these mark-up is generated due to third party javascript libraries. So, markup is something like

   <div class="optWrapper multiple open">
       <ul class="options">
           <li data-val="7"><span><i></i></span><label>Critical Illness</label></li>
          <li data-val="25"><span><i></i></span><label>Critical Illness Insurance</label></li>
         <li data-val="3"><span><i></i></span><label>Critical Illness Silver</label></li>
      </ul>
  </div>

and my jQuery code is

$(".optWrapper li").click(function () {
     alert();
 });

I can't find why this event is not getting called. Please help.

Edit 1

I am guessing this behavior is due to these element are loaded after jquery has downloaded in browser, is it that? if yes, than how could I tackle with it?

Edit 2 These element are dynamically generated after dropdownlist's select event.

The answer of onsubject is correct. Saying to use .on instead of .click.

After jQuery 1.7 the preferred method is .on()

Addition on the answer of @onsubject , because his answer won't work, on dynamically created

".optWrapper li"

Instead of the actual element, use the body or its parent element.

$('body').on('click', '.optWrapper li', function() {
//do something
}

These element are dynamically generated after dropdownlist's select event.

Oops, your event listener attached before creation. As javascript event bubbles up target to document, you can handle that event by listening parent of them. See Direct and delegated events section

Attach event listener to the parent which don't generate dynamically.

$('#someparent').on("click","li.your_target",function(){
    alert();
});

Put your jquery code in $(document).ready(function (){}); It will work fine.

You can use .on instead of .click

$(".optWrapper li").on("click", function () {
     alert();
});

See a working version here: http://codepen.io/ramiror/pen/zGeXPO

Try this solution:

$(document).ready(function(){
    $(".optWrapper ul li").live('click', function(e){
        alert("eureka");
    });
});

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