简体   繁体   中英

trying to append content to DOM element

I'm trying to add a div to a row of content with the click of a button. My code works for the first row but not for any other row. Please help. This is the function for the button:

$(".addMMbtn").each(function() {
        $(this).bind("click",
            function() {
                var thisRow = $(this).closest(".txtContentRow");
                var thisTxt = thisRow.find(".txtContent");
                var cellStr = '<div class = "mmCell prep"></div>';
                $(cellStr).appendTo(thisTxt);
            }
        );
    });

You can see a fiddle of the problem here: http://jsfiddle.net/z7uuJ/

You don't need to loop through the elements to bind the handler:

$(".addMMbtn").live('click', function() {
    var thisRow = $(this).closest(".txtContentRow");
    var thisTxt = thisRow.find(".txtContent");
    var cellStr = '<div class = "mmCell prep"></div>';
    $(cellStr).appendTo(thisTxt);
});

$(".addMMbtn") will only find the elements present on the page and your code will only attach click event handler on them. Since you are adding the elements dynamically you should either use delegate or on (if you are using jQuery 1.7+) for click event to work on them too. Try this

Using delegate

  $('#default').delegate('.addMMbtn', 'click', function() {
      $('<div class = "mmCell prep"></div>')
      .appendTo($(this).closest(".txtContentRow").find(".txtContent"));
  });

Using on

  $('#default').on('click', '.addMMbtn', function() {
      $('<div class = "mmCell prep"></div>')
      .appendTo($(this).closest(".txtContentRow").find(".txtContent"));
  });

Demo

Instead of assigning click event directly on the button you need to use on() :

    $(document).on("click", ".addMMbtn", 
        function() {
            var thisRow = $(this).closest(".txtContentRow");
            var thisTxt = thisRow.find(".txtContent");
            var cellStr = '<div class = "mmCell prep"></div>';
            $(cellStr).appendTo(thisTxt);
        }
    );

In this case event handler will be subscribed to all newly added elements.

Code: http://jsfiddle.net/z7uuJ/5/

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