[英]jquery (hover and load) events binding on dynamically created elements
I am able to bind click
event to element with class name keybox
. 我可以将
click
事件绑定到具有类名keybox
元素。 And this element is generated dynamically. 并且该元素是动态生成的。
$('body').on('click','.keybox', function(){
// some code here
});
But for same element I tried binding hover
and load
event using following code: 但是对于同一元素,我尝试使用以下代码绑定
hover
和load
事件:
$('body').on('hover','.keybox', function(){
// some code here
});
$('body').on('load','.keybox', function(){
// some code here
});
....and its not working as expected. ....并且无法正常工作。
Can someone help with this problem? 有人可以解决这个问题吗? I want to bind
hover
and load
event to my element with class name keybox
and this element is generated dynamically. 我想将
hover
和load
事件绑定到具有类名keybox
元素,并且该元素是动态生成的。
Instead of hover, use mouseenter
and mouseleave
event. 代替悬停,使用
mouseenter
和mouseleave
事件。 Instead of body.load use 代替body.load使用
$(document).ready(function() {
You can use following approach to bind multiple events and get object information via event object . 您可以使用以下方法来绑定多个事件并通过event object获取对象信息。
$('body').bind('click hover load', '.keybox', function(e){
if ( e.type === 'hover') {
// do something
}
else if(e.type === 'click') {
// do something
}
....
});
Make sure you bind events in $(document).ready(function() {}
or load javascript just in bottom of html
document body. 确保在
$(document).ready(function() {}
绑定事件,或仅在html
文档正文底部加载javascript。
Since hover
is deprecated you should use mouseenter
and mouseleave
for load
you can write using event using on
( load
is equivalent to ready
). 由于不建议使用
hover
因此应该使用mouseenter
和mouseleave
进行load
,可以使用on
编写事件( load
等于ready
)。
$(function(){ $(document).on('mouseenter', '.keybox', function () { $(this).css('color','red'); }); $(document).on('mouseleave', '.keybox', function () { $(this).css('color','black'); }); $(document).on('click', '.keybox', function () {// click on dynamically loaded events. $(this).css('color','green'); }); $('#btn').click(function() { $('#parent').append("<div class='keybox'>sample1</div>"); $('#parent').append("<div class='keybox'>sample2</div>"); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> zdhsdhsau </div> <input type="button" id="btn" value="create"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.