0

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

我的代码适用于添加 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',显然所有附加的项目都被删除了。

4

2 回答 2

0

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

$(document).on('mousedown', '.item', function(){
    var $this= $(this);
    timeoutId = setTimeout(function(){ $this.remove() }, 500);
})
于 2014-09-01T18:36:04.483 回答
0

您可以存储 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(); } });

于 2014-09-01T19:02:31.600 回答