我想在动态添加的元素中使用 JQuery
检测滚动。 .on()
方法检测到诸如 click
之类的事件,但似乎无法识别 scroll
事件。
示例: https://jsfiddle.net/cwv9h0ur/
HTML:
<input type="button" id="add" value="add Divs"/>
<div id="container"></div>
Click: <div id="out"></div><br>
Scroll: <div id="out2"></div>
Javascript:
$("#add").on("click",function(){
var div = document.createElement("div");
div.className="childDiv";
div.innerHTML=" TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ";
$('#container').append(div);
})
$("#container").on("click",".childDiv",function (){
$("#out").html("click detected");
setTimeout(function(){$("#out").html("")},300)
});
$("#container").on("scroll",".childDiv",function (){
$("#out2").html("scroll detected");
setTimeout(function(){$("#out2").html("")},300)
});
CSS:
.container, .childDiv {
display:inline-block;
margin: 10px;
background: lightgray;
height: 100px;
width: 80px;
overflow:auto;
}
最佳答案
滚动事件不会冒泡,因此您不能委托(delegate)它。但是,您可以在所有支持它的浏览器上捕获事件:
document.getElementById('container').addEventListener(
'scroll',
function(event){
var $elm = $(event.target);
if( $elm.hasClass('childDiv')){ // or any other filtering condition
$("#out2").html("scroll detected");setTimeout(function(){$("#out2").html("")},300);
}
},
true // Capture event
);
-jsFiddle-
关于javascript - JQuery - 在动态添加/附加元素中监听 "scroll"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388995/