本文介绍了在javascript中将事件附加到动态元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将html数据动态插入到动态创建的列表中,但是当我尝试为动态创建的按钮附加onclick事件时,事件不会触发。解决方案将非常感激。
I'm trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the event is not firing. Solution would be really appreciated.
Javascript代码:
Javascript code:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('btnSubmit').addEventListener('click', function () {
var name = document.getElementById('txtName').value;
var mobile = document.getElementById('txtMobile').value;
var html = '<ul>';
for (i = 0; i < 5; i++) {
html = html + '<li>' + name + i + '</li>';
}
html = html + '</ul>';
html = html + '<input type="button" value="prepend" id="btnPrepend" />';
document.getElementsByTagName('form')[0].insertAdjacentHTML('afterend', html);
});
document.getElementById('btnPrepend').addEventListener('click', function () {
var html = '<li>Prepending data</li>';
document.getElementsByTagName('ul')[0].insertAdjacentHTML('afterbegin', html);
});
});
HTML代码:
<form>
<div class="control">
<label>Name</label>
<input id="txtName" name="txtName" type="text" />
</div>
<div class="control">
<label>Mobile</label>
<input id="txtMobile" type="text" />
</div>
<div class="control">
<input id="btnSubmit" type="button" value="submit" />
</div>
</form>
推荐答案
这是因为您的元素是动态创建的你应该来处理事件。
This is due to that your element is dynamically created and you should event delegation to handle event.
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){//do something}
})
jquery让它更容易:
jquery make it easier:
$(document).on('click','#btnPrepend',function(){//do something})
这是一篇关于事件委托的文章
Here is an article you can read about event delegation event delegation article
这篇关于在javascript中将事件附加到动态元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!