使用 jQuery 向动态创建的元素添加自定义 CSS 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18979908/
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-08-26 22:54:23  来源:igfitidea点击:

Adding custom CSS classes to dynamically-created elements with jQuery

javascriptjqueryhtmlcssdom

提问by Chris Kempen

Let me illustrate my question: I have an external JavaScript library that creates certain HTML elements for me dynamically based on user input and interaction, and I'm looking to write a script that would automatically add a certain class to these dynamically created elements. Assume that I also am unable to edit the external JavaScript library I'm using.

让我来说明我的问题:我有一个外部 JavaScript 库,它根据用户输入和交互为我动态创建某些 HTML 元素,我希望编写一个脚本来自动将某个类添加到这些动态创建的元素中。假设我也无法编辑我正在使用的外部 JavaScript 库。

Is this elegantly possible? If so, how? If not, could this be a side-effect of poor implementation design?

这优雅可能吗?如果是这样,如何?如果不是,这可能是糟糕的实现设计的副作用吗?

I've thought about somehow monitoring the DOM to see when it was updated, and adding the classes to these new elements then, but this seems cumbersome and possibly unnecessary.

我想过以某种方式监视 DOM 以查看它何时更新,然后将类添加到这些新元素中,但这似乎很麻烦,而且可能没有必要。

Thanks in advance for any thoughts / solutions!

提前感谢您的任何想法/解决方案!

Edit:

编辑:

As requested, here's a simplified example of what I'm trying to accomplish with a code sample:

根据要求,这是我尝试使用代码示例完成的简化示例:

// function in external library, assume it cannot be edited!
function addElement() {
    $('body').append($('<div class="newly_created_element"></div>'));
}

// my code, looking to add the class name to the newly-created elements
// from the external function above...
// pseudo-coded as I have no idea how to do this!
$(function(){
    when (new element added) {
        add class "my_own_class";
    }
});

I hope this makes sense!

我希望这是有道理的!

采纳答案by Chris Kempen

For the sake of thoroughness and bringing a clear solution to my question to light, herewith my conclusion. Thank you all for your thoughts and suggestions, I've learnt a lot and clearly got people thinking!

为了彻底和清楚地解决我的问题,在此给出我的结论。谢谢大家的想法和建议,我学到了很多东西,也让人们思考了很多!

Initially I was hoping for a magical jQuery function that I'd perhaps overlooked, something along the lines of:

最初,我希望有一个神奇的 jQuery 函数,但我可能忽略了它,大致如下:

$("#parent-element").monitorDom(function(added_element){ ... });

...but there just isn't anything, which is probably a good thing because I suspect I've stumbled onto poor code design, and allowing for hooks and callbacks is a better way to go. I.e.: use the smaller, established and tested building blocks instead of trying to over-engineer something.

...但是什么都没有,这可能是一件好事,因为我怀疑我偶然发现了糟糕的代码设计,并且允许挂钩和回调是更好的方法。即:使用较小的、已建立和经过测试的构建块,而不是试图过度设计某些东西。

If you don't care about supporting Internet Explorer and it's quirks, you may definitely look at the deprecated mutation events, or their replacement the MutationObserver. Here is also a decently answered SO question with the use of mutators: Is there a JavaScript/jQuery DOM change listener?

如果您不关心支持 Internet Explorer 并且它的怪癖,您肯定可以查看已弃用的突变事件,或者它们的替代品MutationObserver。这里还有一个使用 mutator 回答得体的 SO 问题:是否有 JavaScript/jQuery DOM 更改侦听器?

In a nutshell, as of this post, there is no built-in jQuery function to monitor DOM changes, and in my case my problem can be resolved with better code design. Thank you all for all the answers, and let's keep pushing the limits!

简而言之,在这篇文章中,没有内置的 jQuery 函数来监控 DOM 变化,在我的情况下,我的问题可以通过更好的代码设计来解决。感谢大家的回答,让我们继续挑战极限!

回答by MaVRoSCy

You can do something like:

您可以执行以下操作:

$("body").bind("DOMNodeInserted", function() {
   $(this).find('.newly_created_element').addClass('my_own_class');
});

See more on DOMNodeInserted here

此处查看有关 DOMNodeInserted 的更多信息

回答by kasper Taeymans

Hi I made a jsfiddle dealing with your issue. The click on the button simulates your external libary adding a element. Unrelated to the button click I'm listening on DOMNodeInserted. If there is something inserted in the dom a class is added. You could easily modify the script to only add a class to certain elements.

嗨,我做了一个 jsfiddle 来处理你的问题。单击按钮模拟您的外部库添加元素。与按钮单击无关,我正在侦听 DOMNodeInserted。如果在 dom 中插入了一些东西,则会添加一个类。您可以轻松修改脚本以仅向某些元素添加类。

http://jsfiddle.net/kasperfish/AAd8f/

http://jsfiddle.net/kasperfish/AAd8f/

$(function() {
    $('#btn').click(function(){
        $('body').append('<div style="width:30px;height:30px;border:1px solid black"></div>');
    });


    $(document).on('DOMNodeInserted', function(e) {

        $(e.target).addClass('blue');
    });


});

回答by hvgeertruy

Surely there is a wrapper class or id that library uses that you can use too. Just add css styling to that wrapper. I never found a library where I couldn't hook onto it's wrapper class/id definition.

当然,您也可以使用库使用的包装类或 id。只需将 css 样式添加到该包装器即可。我从来没有找到一个库,我无法连接到它的包装类/id 定义。

Failing that, you need act on changes made by that script. Possibly by adding a listener to a specific user interaction or, like you mentioned, a DOM update. Maybe you can add a listener or callback on the external script itself.

否则,您需要对该脚本所做的更改采取行动。可能通过向特定用户交互或 DOM 更新添加侦听器。也许您可以在外部脚本本身上添加侦听器或回调。

I could give a more accurate answer on that if I knew more about the specific external script.

如果我对特定的外部脚本有更多的了解,我可以给出更准确的答案。

Regarding your snippet: you can listen for DOM updates like this $(".newly_created_element").bind(DOMSubtreeModified, function() { this.addClass('class'); });

关于您的代码段:您可以监听这样的 DOM 更新 $(".newly_created_element").bind(DOMSubtreeModified, function() { this.addClass('class'); });

回答by Ivan Demchenko

If I were you, I would use events. jQuery makes it easy. Here are the first three links from Google: http://www.sitepoint.com/jquery-custom-events/, https://stackoverflow.com/a/14840483/993216, http://api.jquery.com/trigger/.

如果我是你,我会使用事件。jQuery 让这一切变得简单。下面是从谷歌第一三通:http://www.sitepoint.com/jquery-custom-events/https://stackoverflow.com/a/14840483/993216http://api.jquery.com/触发/

In one module you load the data from server, perhaps process it and trigger the event. In another module you can listen to that event and do whatever you need. In my opinion this is the best approach. This is very agile way to build and app because you can add another modules.

在一个模块中,您从服务器加载数据,可能对其进行处理并触发事件。在另一个模块中,您可以收听该事件并执行您需要的任何操作。在我看来,这是最好的方法。这是一种非常灵活的构建和应用方式,因为您可以添加其他模块。

回答by manish

This works fo me, I keep on checking wether that class exists or not ,once it finds it ,the interval function stops

这对我有用,我一直在检查该类是否存在,一旦找到它,间隔函数就会停止

var interval=setInterval(function(){ 
    if($('._icon').children().hasClass('_share')){
      clearInterval(interval);
    }else $('._icon').children().addClass('_share');
}, 1000);