将属性添加到所有新创建的元素

时间:2013-08-21 20:06:30

标签: javascript jquery dom mutation-observers

例如,将具有值target的所有新链接属性_blank添加到具有随机值的所有新<div>属性title。除setTimout()以外的任何想法?

UPD :我需要像.attrGlobal()这样的内容。 This回答只允许使用链接及其属性target ,但是如何对所有元素及其所有属性执行此操作?

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

4 个答案:

答案 0 :(得分:1)

你可以这样做,在这个答案中解释。 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');
});

答案 1 :(得分: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) {将进入永久循环并且浏览器会冻结。

答案 2 :(得分:0)

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

如果按ajax添加,最好将此代码放入成功函数中。

$('#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

答案 3 :(得分:0)

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

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

相关问题