简体   繁体   English

在ajax之后加载元素之后选择一个DOM元素

[英]Selecting a DOM element after The element is loaded after ajax

Assume I need to select .my-class But that is not yet in DOM elements It will load by ajax After complete dom loaded. 假设我需要选择.my-class但是尚未在DOM元素中选择。它将在完成dom加载后由ajax加载。

Now question is How can i get it work after it is loaded. 现在的问题是,加载后如何使它工作。

var class = jQuery('.my-class'); It will not work if called in document ready function . 如果在document ready function调用,它将不起作用。

How can I get It selected?? 我如何选择它?

I don't want to touch ajax function.I want to do it from another js file 我不想触摸ajax函数,我想从另一个js文件中执行

Use parent selector, ie 使用父选择器,即

body 

or 要么

document

In combination with jQuery.fn.on ( see: https://api.jquery.com/on/#on-events-selector-data-handler ) 与jQuery.fn.on结合使用(请参阅: https : //api.jquery.com/on/#on-events-selector-data-handler

But better to use closest parent selector, the one DOM element closest to your dynamic DOM element that won't be loaded dynamically, since that is most efficient. 但是最好使用最接近的父选择器,它是最接近动态DOM元素且不会动态加载的一个DOM元素,因为这样做最有效。

$(parentSelector).on(event, childSelector, function(){
    // whatever you want to do
});

So code would be like: 因此代码如下:

$('.some-parent-class').on('click', '.my-class', function(){
    // whatever you want to do
});

You can use a simple setInterval script to poll for your target selector. 您可以使用简单的setInterval脚本来轮询目标选择器。

var timer = setInterval(timerFunc, 500);

function timerFunc() {
    if ($('.my-class').length){
      clearInterval(timer);
      console.log('exists');
    }
}

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

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