简体   繁体   中英

Create element and event (click)

My code:

<script>
        function abc(){
          for (var i = 0; i < 3; i ++)
          {
             var t = $('<li></li>').text(i);    
             $("ol").prepend(t);
          }
        }
        $(document).ready(function(){
          $("li").click(function(){
            $(this).hide();
          });
        });
</script>

HTML:

<body> 
  <button onclick = "abc()">asdf</button> 
  <p>If you click on me, I will disappear.</p> 
  <ol> 
    <li>Click me away!</li> 
    <li>Click me too!</li> 
  </ol>
</body> 

Why when i click on the created (li) - it doesn't hide? How can i do it?

Because when DOM is loaded there are no <li> elements added yet. You add them on click only.

There are several solutions here. One is to bind event directly to the created element:

for (var i = 0; i < 3; i++) {
    $("<li></li>").text(i).on("click", function() {
        $(this).hide();
    }).prependTo("ol");
}

DEMO: http://jsfiddle.net/Xgr22/

Another way is to use event delegation:

$("ol").on("click", "li", function() {
    $(this).hide();
});

DEMO: http://jsfiddle.net/Xgr22/1/

Try this:

$(document).ready(function(){
      $('ol').on('click','li',function(){
        $(this).hide();
      });
    });

This ensures that all 'li' elements fire the click handler when clicked, whether they are already created, or whether they are created later.

NB: Live is Depreciated!! this is how to do it pre jQuery 1.7

depending in the jQuery version you are using, if it's before 1.7 this will work

 <script>
    function abc(){
      for (var i = 0; i < 3; i ++)
      {
         var t = $('<li></li>').text(i);    
         $("ol").prepend(t);
      }
    }
    $(document).ready(function(){
      $("li").live(function(){
        $(this).hide();
      });
    });
</script>

Try:

$('li').on('click', function () 
{
    $(this).hide();
});

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