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());
});
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:
<li>
to the <ul>
itself. 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.