Jquery .On('click') 不合作

Jquery .On('click') is being uncooperative

我有一个在 div 中生成的删除按钮。单击时,我希望它删除自身和 div 以及其中的所有内容。

$('#geography-save').click(function () {
    $('.selected-criteria').prepend('<div><button type="button" class="btn btn-danger remove-save"><i class="fa fa-times"></i></button><p>Geography Selection</p></div>');
});
$(document).ready(function(){
    $('.remove-save').on('click', function () {
        alert('test');
        $(this).parent('div').remove();
    });
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-success" id="geography-save" data-dismiss="modal">Save Search</button>

<div class="selected-criteria"></div>

只需使用 jQuery 的 on() 方法,如下所示:

$('body').on('click', '.remove-save', function () { ... });

如果内容是在 DOM 结构中动态生成的,您应该将事件绑定到已经存在的父级!

$('#geography-save').click(function () {
    $('.selected-criteria').prepend('<div><button type="button" class="btn btn-danger remove-save"><i class="fa fa-times"></i></button><p>Geography Selection</p></div>');
});
$(document).ready(function(){
    $('body').on('click', '.remove-save', function () {
        alert('test');
        $(this).parent('div').remove();
    });
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-success" id="geography-save" data-dismiss="modal">Save Search</button>

<div class="selected-criteria"></div>

由于您的 button 是动态生成的,您只能基于 static 元素访问它 - 因此您可以使用此:

$('body').on('click','.remove-save', function () {

参见下面的演示:

$('#geography-save').click(function() {
  $('.selected-criteria').prepend('<div><button type="button" class="btn btn-danger remove-save"><i class="fa fa-times"></i></button><p>Geography Selection</p></div>');
});
$(document).ready(function() {
  $('body').on('click', '.remove-save', function() {
    $(this).parent('div').remove();
  });
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<button type="button" class="btn btn-success" id="geography-save" data-dismiss="modal">Save Search</button>

<div class="selected-criteria"></div>