簡體   English   中英

如何讓js知道新創建的html元素

[英]how to let js know about newly created html element

我正在用js創建新的html元素。

$('#write_comment').on('click',function(){
  $(this).html('<textarea> </textarea><button onclick="test()">save</button>');
});

function test(){
 alert('testme');
}

但是在創建了這些textareabutton后,如果我點擊save ,則沒有任何反應。

我可以說有任何jquery功能嗎? (newly_created_element).find(js_function)

那個或具有相同功能的東西會很高興。

請幫忙。

$('#write_comment').on('click',function(){
  $(this).html('<textarea> </textarea><button id="test">save</button>');
});

$('body').delegate('#test','click',function(){
 alert('testme');
});

使用課程

$('#write_comment').on('click',function(){
      $(this).html('<textarea> </textarea><button class="test">save</button>');
    });

    $('body').delegate('.test','click',function(){
     alert('testme');
    });

單獨創建按鈕:

$('#write_comment').on('click',function(){
  var myButton = $('<button>save</button>').click(function() {
    test();
  });
  $(this).html('<textarea></textarea>').append(myButton);
});
$('#write_comment').on('click',function(){
  $(this).html('<textarea> </textarea><button class="NewlyAdded">save</button>');
});

$(document).on在很多方面表現得像.live()delegate() 並將適用於以后添加的元素

$(document).on('click','#write_comment button.newlyAdded',function()
{
  alert('testme');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM