[英]add double click action in html using jquery
I am adding double click action for every li
in a ol
. 我正在为
ol
每个li
添加双击动作。 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
. 然后,我单击按钮以在
ul
添加新行。 The style
works well but double click action cannot work in the added new line. style
效果很好,但双击操作无法在添加的新行中起作用。 Is there a way to add double click action like adding the style
? 有没有办法添加
style
等双击动作? Or there is another way to do this? 还是有另一种方法可以做到这一点?
Try using the on()
in jquery
尝试在
jquery
使用on()
$('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 ). 您可以做的是使用jQuery( source )的
on()
-函数。 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. <li>
附加到<ul>
本身。 Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.