質問

For example add to all new links attribute target with value _blank or to all new <div>s attribute title with random value. Any ideas except setTimout()?

UPD: I need something like .attrGlobal(). This answer allows to do that only with links and their attribute target, but how to do that with all elements and all their attributes?

UPD2: Trying MutationObserver as SLaks recommended but firefox freezes when clicking on add button http://jsfiddle.net/1337/wvfkc/5/.

役に立ちましたか?

解決 2

Finally found solution.

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

In options you need subtree: true always, and if you changes attributes do not add to options attributes: true because MutationObserver(function(mutations, observer) { will go into the eternal cycle and browser freezes.

他のヒント

You can do like is explained in this answer. jQuery: Is there a way to automatically add attributes to dynamically generated HTML, in the same way that live() works with events?

Since .live is deprecated, use .on instead.

Use .on to accomplish what you are looking to do with the links like so

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

The answer depends on how you add the new elements so jQuery can find them. To answer more precise we would need to know also the parent of the elements and if there are other elements that should not get changed.

If you add by ajax, the best would be to put this code in the success function.

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

is this what you're trying to do? (assuming clicking a button inserts new elements)

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top