javascript - 如何从具有大量元素的类中删除一个元素?

标签 javascript jquery

我有多个 .note,并且我希望能够单击 .remove(位于每个 .note 中)并且它将删除我单击的 .remove 所在的 .note。我已经使用 .closest() 来做到这一点,但它仅适用于第一个音符,不适用于之后的其他音符。提前致谢!

这是代码:

删除.note的代码:

$('.remove').click(function () {
    $(this).closest('.note').remove(".note");
});

HTML:

<body>
<div id="wrapper">
    <div id="wrp">
         <h1>Click to make a new note!!!</h1>

        <hr>
        <div class="note">
            <p class="remove"><b>X</b>

            </p>
            <div class="time"></div>
            <hr>
            <textarea class="item"></textarea>
            <div class="saved"><span class="msg"></span>

            </div>
        </div>
</body>

JS:

$('.note').click(function (event) {
event.preventDefault();
});

$('#wrp, #wrapper').click(function showNote() {
$('.note').fadeIn();
});

$(function () {

$(document).mousedown(function (event) {
    // only proceed if clcik is not anywhere in a note element
    if (!$(event.target).closest('.note').length) {
        var note2 = $('.note').first();
        note2.clone().insertBefore(note2);
        console.log(note2);
    }
});
});

$('.remove').click(function () {
$(this).closest('.note').remove(".note");
});



window.onload = function () {
var input = $("#item").focus();
};



function date() { //code indentation
var now = new Date();
now2 = now.getMonth() + 1 + '/' + now.getDate() + '/' + now.getFullYear() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
$('.time').html(now2);
}
date();

var autosaveOn = false;

function myAutosavedTextbox_onTextChanged() {
if (!autosaveOn) {
    autosaveOn = true;
    $('.item').everyTime("3000", function () {
        $.ajax({
            type: "POST",
            url: "/echo/html/",
            data: "id=1",
            success: function (msg) {
                $('.msg').text(Saved);
                alert("saved");
            }
        });
    }); //closing tag
}
}
$(".note").closest('.note').draggable();

$(function () {
$("#tabs").autoSave(callback, ms);
});
$(".item").autoSave(function () {
var time = new Date().getTime();
$("#msg").text("Draft Autosaved " + time);
}, 500);

最佳答案

看起来您有一个注释,然后当您单击该注释以外的其他内容并将其插入到上一个注释旁边时,您正在克隆它。由于您只绑定(bind)到第一个音符,因此您需要使用实时函数。例如。类似的东西

 $('body').on('click', '.remove', function() {
   $(this).closest('.note').remove(); 
 });

关于javascript - 如何从具有大量元素的类中删除一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30378488/

相关文章:

javascript - Material UI 全局 css 变量

javascript - jQuery 克隆问题

javascript - 仅在桌面模式下激活 jquery 功能?

javascript - 创建适用于任何选择器的自定义事件

javascript - JQuery AJAX + C CGI

javascript - 当元素插入 html OL 时触发事件

javascript - 将 Backbone.Layout 定义为 require js 模块?

javascript - HTML - PHP 中的 'onclick' 确认函数

javascript - 如果语句不能正常工作

javascript - 如何使用 Javascript 或 JQuery 更改 HTML IFrame 元素属性