简体   繁体   English

如何让js知道新创建的html元素

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

i am creating new html element with js. 我正在用js创建新的html元素。

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

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

but after these textarea and button were created, if i click on save , nothing happens. 但是在创建了这些textareabutton后,如果我点击save ,则没有任何反应。

is there any jquery function where i can say. 我可以说有任何jquery功能吗? (newly_created_element).find(js_function) ? (newly_created_element).find(js_function)

that or something with same functionality would be nice to have. 那个或具有相同功能的东西会很高兴。

please help. 请帮忙。

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

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

Using class 使用课程

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

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

Create the button seperately: 单独创建按钮:

$('#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 behaves like .live() or delegate() in many ways. $(document).on在很多方面表现得像.live()delegate() And will work for elements that are added later . 并将适用于以后添加的元素

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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