当我按下删除按钮时,如何让父div删除

时间:2018-01-05 08:51:41

标签: javascript jquery html css

我正在尝试创建一个删除按钮,删除其父div及其中的所有内容

function remove() {
  var $this = $(this).closest();
  //console.log($this)
  $this.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-color: green;">
  <div>NAME</div>
  <div><button onclick="remove">Remove</button>
  </div>
</div>

然而,每当我按下按钮时,都没有任何反应。

编辑:

$(function() {
  $('button').click(function() {
    var $this = $(this).closest('.container');
    $this.remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div>NAME 1</div>
  <div><button>Remove</button></div>
</div>
<div class="container">
  <div>NAME 2</div>
  <div><button>Remove 2</button></div>
</div>

没有任何反应,也没有错误发生。

编辑2:

这是我的整个javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script type="text/javascript">
var csrftoken = Cookies.get('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
var suggested_students = $("#suggested_students");
var search_bar = $('#search_bar');

function clear(){
    suggested_students.empty(); 
    search_bar.val('');
}

search_bar.keyup(function () {

    var keyword = search_bar.val();
    if(keyword.length > 2){
        //console.log('hey')
        var url = window.location.pathname;
        $.ajax({
            method: 'GET',
            url: url,
            data: {
            'keyword': keyword,
            },
            dataType: 'json',
            success: function (data) {
                suggested_students.empty(); 
                var suggestions = data.students;
                for(i = 0; i< suggestions.length; i++){
                    var current_student = suggestions[i];
                    var div = $("<a href='#'><div/></a>");
                    div.data("name", current_student[0]);
                    div.data("id", current_student[1]);
                    div.html(current_student[0] + "<br/>");
                    div.on("click", moveProfile);
                    div.css({"background-color": "green"});
                    suggested_students.append(div);
                }
            }
            })
        }else if(keyword.length == 0){
            clear()

        }
    })

var students_to_add = $("#students_to_add")

function moveProfile(){
    var $this = $(this);
    var studentID = $this.data("id");
    var studentName = $this.data("name");
    var div = $("<div/>");
    div.data('id', studentID);
    div.data('name', studentName);
    div.html("<div>" + studentName +"</div><div><button>Remove</button></div>");
    div.css({"background-color": "green"});
    div.addClass("container")
    students_to_add.append(div);    
    clear()
}


$(function() {
    $('button').click(function() {
      var $this = $(this).closest('.container');
      $this.remove();
    });
  });


</script>

这是整个HTML:

<div>
    <label>Set Name: </label>
    <input type="text" class="class_name" id='class_name'/>
</div>
<br>

<div class='student_search_bar'>
    <label for='search_bar'>Search for Students: </label>
    <input type="text" class="student_search_bar_bar" id='search_bar'/>   
</div>
<br>
<div id='suggested_students'>

</div>

<div id='students_to_add'>
    <label>Students to add: </label>

</div>

我有一个函数从AJAX调用中获取一个列表并将其转换为多个div,如下所示:

<div class="container">
  <div>NAME</div>
  <div>
    <button>Remove</button>
  </div>
</div>

我的Javascript低于我的html,并且都在同一个文件中。

当我运行Rory McCrossan建议的代码时,我在控制台中没有错误,当我使用console.log来查看函数是否被调用时,没有打印任何内容。

4 个答案:

答案 0 :(得分:3)

使用on*事件属性时,this引用将是窗口,而不是单击的元素。此外,closest()需要选择器。

要解决此问题,请将不显眼的事件处理程序附加到button。当您动态附加button元素时,您需要使用委托事件处理程序,如下所示:

&#13;
&#13;
$(function() {
  $('#students_to_add').on('click', 'button', function() {
    var $this = $(this).closest('.container');
    $this.remove();
  });
});
&#13;
.container {
  background-color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="students_to_add">
  <div class="container">
    <div>NAME</div>
    <div>
      <button>Remove</button>
    </div>
  </div>
  <div class="container">
    <div>NAME</div>
    <div>
      <button>Remove</button>
    </div>
  </div>
  <div class="container">
    <div>NAME</div>
    <div>
      <button>Remove</button>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以将此代码更改为此类

<div id="box" style="background-color: green;">
    <div>NAME</div>
    <div><button data-remove="#box">Remove</button>
    </div>
</div>

并使用以下代码,您可以使用具有数据删除属性的所有元素的通用方法

$(function() {
    $('[data-remove]').on('click', function() {
        $($(this).data('remove')).remove();
    });
});

如果你想使用closest,你应该添加适当的类来识别要处理的元素。

<div class="box" style="background-color: green;">
    <div>NAME</div>
    <div><button class="close-box">Remove</button>
    </div>
</div>

使用此脚本

$(function() {
    $('.close-box').on('click', function() {
        $(this).closest('.box').remove();
    });
});

答案 2 :(得分:0)

您需要在closest()

中传递选择器

<强> HTML

<button onclick="remove(this)">Remove</button>
                   ----^^^^^^---- here

<强>的Javascript

function remove(ele){
    var $this = $(ele).closest('div');
    //console.log($this)
    $this.remove();

}

但是,这将从按钮中删除最近的div。我不确定你要删除哪个div。您可以为要删除的div提供ID,然后使用该ID。

例如:

<div style="background-color: green;" id="some-id">

var $this = $(ele).closest('#some-id');

更好的方式:

$('button').click(function() {
  var $this = $(this).closest('div');
  $this.remove();
}); 

答案 3 :(得分:0)

为函数提供适当的括号,如下所示。

<div><button onclick="remove()">Remove</button>
相关问题