简体   繁体   English

使用jquery将滑动事件添加到动态加载的内容中

[英]Adding swipe event to dynamically loaded content with jquery

Here is a js fiddle showing the problem. 这是一个显示问题的小提琴。

http://jsfiddle.net/4CLqY/4/ http://jsfiddle.net/4CLqY/4/

The swipe works fine on the red box but not on the new blue box which is created after pressing the new button. 滑动在红色框上工作正常,但在按下新按钮后创建的新蓝框上没有。 (swipe across red box with mouse for change) (用鼠标滑过红框以便更改)

Sorry if this a dupe but I have not found any solution online which solves my particular issue. 对不起,如果这是一个骗局,但我没有找到任何解决我的特定问题的解决方案。

The code is from the touchSwipe site 代码来自touchSwipe网站

javascript JavaScript的

 $(function() {      
  //Enable swiping...
  $(".test").swipe( {
    //Generic swipe handler for all directions
    swipe:function(event, direction, distance, duration, fingerCount) {
      $(this).text("You swiped " + direction );  
    },
    //Default is 75px, set to 0 for demo so any distance triggers swipe
     threshold:0
  });
});

$(document).on('click','button',function(){


$('<div class="test" id="test2">Swipe me</div>').appendTo('body');

});     

HTML HTML

<div class="test">Swipe me</div>

<button>New</button>

You can reattach the swipe event to the new elements, because they don't exist when you add the initial event. 您可以将滑动事件重新附加到新元素,因为在添加初始事件时它们不存在。

Try this fiddle . 试试这个小提琴

I added a addSwipeTo function that takes a selector, and adds the event to the elements it matches. 我添加了一个addSwipeTo选择器的addSwipeTo函数,并将事件添加到它匹配的元素中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM