简体   繁体   English

使用动态加载的内容触发点击事件

[英]Trigger a click event with dynamically loaded content

My content changes with ajax and I want that after 200px of scrolling to trigger a click to an element. 我的内容随着ajax的变化而变化,我希望在滚动200px后触发对元素的点击。

$(window).scroll(function() {
  if($(window).scrollTop() > 200){
    $(".element")[0].click();
  }
}

But this does not work with changing content. 但这不适用于更改内容。 On first load it works. 首次加载时有效。 But as soon as ajax does it's stuff the event isn't firing anymore. 但是,一旦ajax生效,该事件就不再触发。 Any ideas? 有任何想法吗? I know about the on event but cannot figure it out how to use it here. 我知道on事件,但无法在这里弄清楚如何使用它。

Update 更新资料

The linked question does not help me: 链接的问题对我没有帮助:

$(staticAncestors).on(eventName, dynamicChild, function() {});

this works for clicks or other events. 这适用于点击或其他事件。 But I don't want to attach a click event, I want to trigger a click event. 但我不想附加点击事件,我想触发点击事件。 How could I do it? 我该怎么办? The change is in an ajax call beyond my control so I cannot add a callback. 更改发生在我无法控制的ajax调用中,因此我无法添加回调。

Thanks 谢谢

When you're trying to play with item/object's that aren't there on the very first load JavaScript gets a bit confusing. 当您尝试使用第一次加载时不存在的项目/对象时,JavaScript会有些混乱。

jQuery/JS language in simple terms only really can apply to the objects on page load. 简单来说,jQuery / JS语言只能真正应用于页面加载时的对象。

The easiest way around this is to delegte functions to a HTML element that is always there on pageload. 解决此问题的最简单方法是将函数委派给页面加载中始终存在的HTML元素。 Most people usually use the <body> . 大多数人通常使用<body>

Eg: 例如:

$(window).scroll(function() {
  if($(window).scrollTop() > 200){
    $( "body" ).delegate( $(".element")[0], "click", function() {
      // Your Code Here
    });
  }
}

根据此答案 ,您可以使用find()方法查看静态祖先元素的后代元素:

$('#someStaticAncestorElement').find('.element')[0].click();

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

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