【问题标题】:Add attribute to all newly created elements [closed]为所有新创建的元素添加属性[关闭]
【发布时间】:2013-08-24 08:54:05
【问题描述】:

例如,将值_blank 添加到所有新链接属性target 或使用随机值添加到所有新<div>s 属性title。除了setTimout(),还有什么想法吗?

UPD:我需要.attrGlobal() 之类的东西。 This answer 只允许对链接及其属性 target 执行此操作,但是如何对所有元素及其所有属性执行此操作?

UPD2:尝试将MutationObserver 设为SLaks recommended,但点击添加按钮http://jsfiddle.net/1337/wvfkc/5/ 时Firefox 冻结。

【问题讨论】:

  • “新链接”是什么意思?动态添加?
  • 和 setTimeout 有什么关系呢?这些元素是如何添加的?请向我们展示代码。
  • 你是如何创建这些元素的?
  • 您正在寻找MutationObserver
  • 最好的方法是在创建元素时添加属性,这就是我们询问您如何创建元素的原因

标签: javascript jquery dom mutation-observers


【解决方案1】:

终于找到解决办法了。

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function() {
  $("a").attr("target", "_blank");
  $("div").attr("title", Math.floor(Math.random() * 1000));
});

observer.observe(document, {
  subtree: true,
  childList: true
});

jsfiddle.net

在选项中您始终需要subtree: true,如果您更改属性,请不要添加到选项attributes: true,因为MutationObserver(function(mutations, observer) { 将进入永恒循环并且浏览器冻结。

【讨论】:

  • +1 我很难理解为什么当我在观察者块中有 'attributes: true' 时 Firefox 一直冻结!现在检测变化是小菜一碟!
【解决方案2】:

这是你想要做的吗? (假设单击按钮会插入新元素)

function setAttrs() {
    $('a').attr('target', '_blank');
    $('div').attr('title', new Date().getTime());
}
$(function() {
    setAttrs();
    $('button').on('click', function(e) {
        e.preventDefault();
        $('body').append('<div>text</div> <a href="//google.com">google</a>');
        setAttrs();
    });
});

FIDDLE

【讨论】:

  • 添加了内容但没有点击怎么办?如果点击了某些内容但内容异步添加了怎么办?
  • 只需在添加内容时调用setAttrs 函数。如果是异步添加,那么函数调用应该在ajax请求的成功回调函数中执行。
【解决方案3】:

答案取决于您如何添加新元素以便 jQuery 可以找到它们。为了更准确地回答,我们还需要知道元素的父级以及是否还有其他不应更改的元素。

如果通过ajax添加,最好将这段代码放在success函数中。

$('#parentDivID a').prop('target', '_blank'); //this changes the atributes of all a element
$('#parentDivID div').prop('title', Math.floor(Math.random()*1000); //give random nr to title

【讨论】:

    【解决方案4】:

    您可以这样做,此答案中对此进行了说明。 jQuery: Is there a way to automatically add attributes to dynamically generated HTML, in the same way that live() works with events?

    由于 .live 已弃用,请改用 .on

    使用.on 来完成您希望通过这样的链接执行的操作

    $('a').on("click", function(e) {
       $(this).attr('target', '_blank');
    });
    

    【讨论】:

    • 除了 .live 已被弃用,所以使用 .on() -- 几乎相同。
    • .live() 已弃用大声笑。但我期待这个答案。
    • ops 这不适用于新创建的jsfiddle.net
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多