在我的页面上,当您在元素上向右滑动时,该元素将会移动。我有以下代码来处理这些滑动:
window.addEventListener("touchstart", touchStart, false);
window.addEventListener("touchmove", touchMove, false);
问题是,它不仅仅影响我想要可滑动的元素。相反,如果我在页面上的任意位置滑动,它将运行 touchMove
。为了解决这个问题,我尝试了:
var content = document.getElementById("content");
content.addEventListener("touchstart", touchStart, false);
content.addEventListener("touchmove", touchMove, false);
这种方法有效,但是当在 #content
上显示 div(通过用户交互)时,事件仍然会触发。
我考虑的另一个解决方案是将这些事件绑定(bind)到 #content
中的元素,这些元素应该启用滑动。问题是,这些元素是动态添加到页面的,因此当在页面加载时调用上面的函数时,不会考虑这些元素。然后我考虑使用 jQuery 的 .on()
方法,如下所示:
$("#content .row").on("touchmove", touchMove, false);
但这根本没有调用 touchMove
。
有没有更好的方法来完成这一切?当事件监听器仅分配给 #content
时,在不是 #content
子元素的元素上调用 touchMove
是否有意义?
最佳答案
通过将事件附加到文档并为所需元素提供过滤器来尝试这种方式。
$(document).on("touchmove", "#content .row", touchMove);
根据评论编辑,可以这样获取事件
$(document).on("touchmove", "#content .row", function(event){
alert(event.target.id);
});
关于javascript - 为动态元素添加事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12984175/