使用 jquery 处理多个事件,我需要添加元素,但在该元素上不会触发单击事件。我也尝试在就绪函数中添加监听器,但它不起作用。请大家帮忙。
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('div.list').append('<div class="item-next">' + toAdd + '</div>')
});
});
$('.item-next').click(function(){
alert()
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Find Listeners</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h2>Find Listeners</h2>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<button id="button">Click to Add</button>
<br/><br/><br/>
List
<div class="list"></div>
</body>
</html>
最佳答案
附加事件元素不适用于正常点击。因此请尝试使用 on()
kindly see the important of that
$(document).on()
学习on()
很有帮助 Why use jQuery on() instead of click()
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('div.list').append('<div class="item-next">' + toAdd + '</div>')
});
});
$(document).on('click','.item-next',function(){
alert('its work')
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Find Listeners</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h2>Find Listeners</h2>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<button id="button">Click to Add</button>
<br/><br/><br/>
List
<div class="list"></div>
</body>
</html>
关于javascript - onclick 监听器不适用于动态 dom 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41072732/