简体   繁体   中英

add double click action in html using jquery

I am adding double click action for every li in a ol . the code is:

  <style>
  li:hover {
      cursor: pointer;
      background-color: yellow;
  }
  </style>
  <script>
      $(function() {
          $('#myol li').dblclick(function() {
             alert($(this).text()); 
          });   
      });
      function myclick() {
          $("#myol").append("<li>item</li>");
      };
  </script>
</head>
<body>
    <ol id="myol">
        <li>Item 1</li>
    </ol>
    <button type="button" onclick="myclick()">Button</button>
</body>

It works well after the page loading. Then I click the button to add a new line in ul . The style works well but double click action cannot work in the added new line. Is there a way to add double click action like adding the style ? Or there is another way to do this?

Try using the on() in jquery

$('body').on('dblclick','#myol li', function() {
             alert($(this).text()); 
          });  

To make double click work to the appended line, you need to do it like so :

$('#myol').on('dblclick', 'li', function() {
     alert($(this).text()); 
});`

You have to change the way you bind your event.

The way you bind it now, it doesn't check for newly added elements, but only binds to those who are there already.

What you can do, is use the on() -function from jQuery ( source ). This uses Event Delegation.

Your code would be rewritten to

$("#myol").on("dblclick", 'li',function() {
    alert($(this).text()); 
});   

JsFiddle

You need to use event delegation, since you are creating the elements dynamically. Normal event binding will only work with the elements which is present at the time of executing the event binding code.

 $('#myol').on('dblclick', "li", function() {
   alert($(this).text());
 });

You want to add additional list items when clicking on the existing ones. Try this code:

$('#myol').on('dblclick', 'li', function() {
   $("ul").append('<li>My added text</li>');
 });

You need to know that:

  • You can just append the <li> to the <ul> itself.
  • You need to use the opposite type of quotes than what you're using in your HTML. So since you're using double quotes in your attributes, surround the code with single quotes.

Hope it helps.

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