简体   繁体   中英

How to add text to dynamically created DOM objects?

Say I have two buttons "Add Link" and "Add Text". The "Add Link" button automatically appends the following to the existing page:

<a href="text.html"></a>

When i click on the button "Add Text", the text of all dynamic links created should contain the text "Text".

I originally use "$("a").text("Text")" for the function of the "Add Text" button, but it does not work because the links are dynamically created as the user clicks the "Add Link" button.

How do I make it so that I can get "Text" into all of the dynamically created link?

NOTE: Something Like this

$('buttonforaddtext').live('click', function() {
    $("a").text("Text");
});

Does not work for me because the button has been there the whole time, its the "a" that are dynamically created with the click of the "Add Link" button.

$('button').on('click', function() {
   /* your code */
});

If you have dynamic object you need to use .on() to let it work...

Try like below as I mentioned in comment,

$('#addLink').on('click', function () {
    $(body).append('<a href="' + someURL + '" class="newLink"></a>');
});

$('#addText').on('click', function () {
    $('a.newLink').text('New Link'); 
});
var yourLink = $("<a href="+someURL+">"+yourText+"</a>");

or

var yourLink = $("<a href="+someURL+"/>");
yourLink.html("Text");

then

yourLink.appendTo($('body'));

Thats if you wish to create @ the same time

That you describe sounds fine to me. Maybe you should post the code you are using. The follow should work:

$('#addLink').click(function(){
    $('body').append('<a href="text.html"></a>');
});

$('#addText').click(function(){
    $('a').text('Text');
});

As long as your jQuery object ($('a')) is being created after the click event has happened, everything should work as you describe.

You need to use '.live' method, as our colleague said before. It happens that in the moment you are trying to bind the event, the element doesn't exis and it dosn't work.

Using .live, the window will keep listening for the element you've selected.

In the case you're using jQuery 1.7.+, I recomend you use the .on() method to bind the event and the .off() to unbind it as soon you dont need it anymore...

PS.: By the way, what are you trying to select?

$('buttonforaddtext')

Your problem is probably that live is beyond deprecated or you don't have the HTML that you think you have. Since you re-query the A tags in your callback for the text insertion and the button is static HTML, you shouldn't need 'live' or 'delegate' or 'on'. Just do a simple .click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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