Jquery .On('click')不合作

时间:2016-12-23 16:54:42

标签: javascript jquery html twitter-bootstrap removeall

我有一个在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>

2 个答案:

答案 0 :(得分:3)

只需使用jQuery的on()方法:

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

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

&#13;
&#13;
$('#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();
    });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

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

见下面的演示:

&#13;
&#13;
$('#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();
  });
});
&#13;
<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>
&#13;
&#13;
&#13;