简体   繁体   English

自动为动态添加的html元素添加属性

[英]automatically add attributes to dynamically added html elements

I need to add dir=auto to several ul element that are being added dynamically when several events happen. 我需要将dir=auto添加到几个事件发生时动态添加的ul元素。

Since these events are not in my control (some are plug-ins, some are ajax results, etc) I don't want to add a line of code sporadically 由于这些事件不在我的控制之下(有些是插件,有些是ajax结果等)我不想偶尔添加一行代码

how can I add $("ul").attr("dir","auto") in a way that any of the relevant elements will have the attributes once they are added to page? 如何添加$("ul").attr("dir","auto") ,以便任何相关元素在添加到页面后都具有属性?

If I understand you correctly, you need to add a listener to the document/dom to know once the <ul> has been added dynamically, then check if that <ul> has been modified as well later after load (to add other attri to them?) . 如果我理解正确的话,你需要在文件/ dom中添加一个监听器,以便在动态添加<ul>知道,然后在加载后检查是否已经修改了<ul> (添加其他attri到他们?)

The listener should work once <ul> is being modified or being added to the document, then filter/select the <ul> and apply your .attr function. 一旦<ul>被修改或被添加到文档中,侦听器就应该工作,然后过滤/选择<ul>并应用你的.attr函数。 Check this and this 检查这个这个

I've tested the code on my console for this SO page and it seems to be working. 我在我的控制台上为这个SO页面测试了代码,它似乎正在工作。 I'm using FF26, therefore something like this might help: 我正在使用FF26,因此这样的事情可能会有所帮助:

    //listen to parent to know if it's being modified. you can listen to <ul> if you want to check if it has modified if you want to do something with <li> for example. 
    $("#parentDiv").bind("DOMSubtreeModified", function() {
       //your code here       
        $("ul").attr("dir","auto");// to all <ul> in the page
        //or only filter ul that belongs to this div
       // this.find("ul").attr("dir","auto");
    });

I think this answer has more accurate findings since ( DOMSubtreeModified ) seems to be deprecated (although it just worked fine). 我认为这个答案有更准确的发现,因为( DOMSubtreeModified )似乎已被弃用(尽管它运作良好)。

If the <ul> is going to be added later (unknown time) then in my opinion, you have two options: 如果<ul>将在稍后(未知时间)添加,那么在我看来,您有两个选择:

  1. Add the listener to body or parent div that holds the <ul> and monitor when <ul> is added then apply your attr. 添加听者body或家长的div持有<ul>当监视<ul>添加应用您ATTR。
  2. Add a setInterval to keep checking if there is any <ul> in the page every a few sec? 添加一个setInterval来检查页面中是否每隔几秒就有<ul>

I prefer option 1, because I've read that option 2 (using setInterval ) might add some overhead. 我更喜欢选项1,因为我读过选项2(使用setInterval )可能会增加一些开销。 Ref. 参考。 .

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

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