javascript 等到 HTML 元素得到一个类然后做一些事情

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10334838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:31:30  来源:igfitidea点击:

Wait until HTML elements gets a class then do something

javascriptjqueryhtml

提问by k0pernikus

I am waiting for the document.ready event in order to do something on my page.

我正在等待 document.ready 事件以便在我的页面上做一些事情。

Alas some other script, which I cannot change, has not worked its magic yet once my script is called. Hence, jquery selection on the class name fails as the class does not yet exist in the DOM.

唉,我无法更改的其他一些脚本在调用我的脚本后还没有发挥其魔力。因此,jquery 对类名的选择失败,因为 DOM 中尚不存在该类。

This is why I want tell my function to listen until an element gets a certain class, then do something with it.

这就是为什么我想告诉我的函数在一个元素获得某个类之前一直监听,然后用它做一些事情。

How do I achieve this?

我如何实现这一目标?

采纳答案by Toni Michel Caubet

You could trigger some event once you added the class.

添加课程后,您可以触发某些事件。

Example:

例子:

$('#ele').addClass('theClass');
$(document).trigger('classGiven')


$(document).bind('classGiven',function(){
    //do what you need
});

回答by adeneo

Something like this (pseudo code) :

像这样(伪代码):

var timer = setInterval(function() {
   if (element.className=='someclass') {
       //run some other function 
       goDoMyStuff();
       clearInterval(timer);
   }
}, 200);

or listen for the element to be inserted:

或侦听要插入的元素:

function flagInsertedElement(event) {
   var el=event.target;
}
document.addEventListener('DOMNodeInserted', flagInsertedElement, false);

jQuery version:

jQuery 版本:

$(document).on('DOMNodeInserted', function(e) {
    if (e.target.className=='someclass') { 
        goDoMyStuff();
    }
});

There's also the liveQueryplugin:

还有liveQuery插件:

$("#future_element").livequery(function(){
    //element created
});

Or if this is a regular event handler, delegated events with jQuery's on();

或者,如果这是一个常规事件处理程序,则使用 jQuery 的 on() 委托事件;

回答by kernelpanic

I'm sorry if I got your question wrong but why not just doing something plain as this on document.ready ? :

如果我问错了你的问题,我很抱歉,但为什么不在 document.ready 上做一些简单的事情呢?:

$("#myelement").addClass('myclass');

if($("#myelement").hasClass('myclass')) {
    alert('do stuff here');
}