【问题标题】:jQuery/Javascript - Edit and delete appended elements by different click timesjQuery/Javascript - 通过不同的点击时间编辑和删除附加的元素
【发布时间】:2014-09-01 18:26:17
【问题描述】:

我想创建一个列表,用户可以通过单击按钮在其中添加元素,通过单击元素更改颜色并通过长按元素删除它们。

我的代码可以很好地添加 div 和更改它们的颜色:

$(document).ready(function(){
$('button').click(function(){
    var toAdd = $('input[name=shop-item]').val();
    if (toAdd == ''){
        return false;
    }
    else {
        $('#list').append('<div class="item item-red">' + toAdd + '</div>');
    });

$(document).on('click', '.item', function(){
    $(this).toggleClass('item-red');
    $(this).toggleClass('item-green');
});

但是我希望能够通过长按删除单个 div。我发现了一些类似下面的例子:

var timeoutId = 0;
$(document).on('mousedown', '.item', function(){
    timeoutId = setTimeout(function(){ $(this).remove() }, 500);
}).bind('mouseup mouseleave', function() {
    clearTimeout(timeoutId);
});

但是,它不适用于“this”。但是如果我改用'.item',显然所有附加的项目都会被删除。

【问题讨论】:

    标签: javascript jquery append long-click


    【解决方案1】:

    在您的 setTimeout 函数中,您处于不同的范围内。 this 有不同的含义。您可以改为缓存它:

    $(document).on('mousedown', '.item', function(){
        var $this= $(this);
        timeoutId = setTimeout(function(){ $this.remove() }, 500);
    })
    

    【讨论】:

      【解决方案2】:

      您可以存储 mousedown 事件时间戳 每个事件的原型中都有时间戳

      var mouseDownTimestamp = 0 $(document).on('mousedown',function(event){ mouseDownTimestamp = event.timeStamp;} ); $(document).on('mouseup',function(event){ //if the mouse up is after 499ms if(mouseDownTimestamp < event.timeStamp - 499){ //or $(event.target).remove(); //or $(event.target).closest('.class of the holder').remove(); $(selector).remove(); } });

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 2021-06-17
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-10
        • 2015-06-21
        相关资源
        最近更新 更多