一个简单的问题:
当我使用
时$(document).on('click', '.btn-del-top', function(e) {})
粉碎工作,但如果我使用
$('.btn-del-top').on('click', function(e) {})
没什么工作。有解释吗?
答案 0 :(得分:3)
可能是因为btn-del-top
元素是动态创建的,或者是在$('.btn-del-top').on('click', function(e) {})
代码执行后创建的。
Demo1:在这种情况下它无效,因为代码不在dom ready
中答案 1 :(得分:0)
主要原因是当你运行第二个代码片段时,元素还不存在,所以找不到它们,所以它们没有被连接起来。第一个代码段在查看document
上的点击之前不会查找它们(例如,可能要晚得多)。
找不到原因可能会有所不同:
如果您查找它们的代码位于上面的 中,那么它们将在HTML中定义,它们将不存在。例如:
<!-- Won't work, the element doesn't exist when you look for it -->
<script>
$('.btn-del-top').on('click', function(e) {})
</script>
<span class="btn-del-top">...</span>
可是:
<!-- Will work, the element exists when you look for it -->
<span class="btn-del-top">...</span>
<script>
$('.btn-del-top').on('click', function(e) {})
</script>
和
<!-- Will work also work, jQuery will call your code later when
all elements in the markup have been created -->
<script>
$(function() { // shortcut for `$(document).ready(...)`
$('.btn-del-top').on('click', function(e) {})
});
</script>
<span class="btn-del-top">...</span>
如果您使用代码创建以后,那么当您尝试将它们连接起来时,它们将不会存在。
答案 2 :(得分:0)
如果您动态添加.btn-del-top,则第二个在该元素存在之前绑定,因此它不会绑定。