在`select`中更改`option`的父级会删除事件

时间:2015-02-10 10:25:41

标签: jquery html

我有两个select列表。 我通过jquery(1.9.X)填充第一个,并在每个dblclick项目中添加option个事件。

预期的行为是:“当用户双击项目到List1时,该项目应该'跳转'到List2,反之亦然”

问题是,当一个项目“跳转”到List2时,该事件似乎将其自我解除绑定。

这是一个小提琴:http://jsfiddle.net/athafoud/7buedvnd/

2 个答案:

答案 0 :(得分:3)

如果您希望双击处理程序能够在removeappend中生存,请不要这样做。 remove()也会断开所有事件处理程序。

虽然你可以通过简单地删除remove()来解决这个问题(如@Arun P Johny建议的那样),但最好还是在列表上使用委派处理程序:http://jsfiddle.net/TrueBlueAussie/j08LLpqe/2/

for (i = 0; i < 10; i++) {
    var item = $('<option></option>').attr('value', i).html(i);
    $('#list1').append(item);
}
$('#list1,#list2').on('dblclick', 'option', function (event) {
    if ($(this).closest('#list1').length > 0) {
        console.log('onList1');
        // Item resides on the left list
        $(this).remove().appendTo("#list2");
    } else {
        console.log('onList2');
        // Item resides on the right list
        $(this).remove().appendTo("#list1");
    }
});

这些工作通过监听事件冒泡到目标元素(列表)然后在事件时应用选择,然后将函数应用于{{1}导致事件的。结果是他们可以动态地在列表之间移动,而您不需要单独的处理程序。

更新。您可以使用optionhas()简化“列表检查”:

remove() is redundant as append will move an element in the DOM

e.g。 http://jsfiddle.net/TrueBlueAussie/j08LLpqe/5/

您当然可以继续减少代码,但在某些时候您需要决定您希望它的可读性。例如这将在一行中完成相同的工作:http://jsfiddle.net/TrueBlueAussie/j08LLpqe/7/

if ($('#list1').has(this).length) {

答案 1 :(得分:1)

我认为问题是.remove(),它将删除与被删除元素相关联的数据,这将导致事件未注册

  

除了元素本身,所有绑定事件和jQuery   与元素相关联的数据将被删除。

for(i = 0; i < 10; i++) {
    var item = $('<option></option>').attr('value', i).html(i);

    // Append Event
    item.off('dblclick');
    item.on('dblclick', function(event) {
        console.log('dbClicked');
        if($(this).closest('#list1').length > 0)
        {
            console.log('onList1');
            // Item resides on the left list
            $(this).appendTo("#list2");
        }
        else
        {
            console.log('onList2');
            // Item resides on the right list
            $(this).appendTo("#list1");
        }
    });


    $('#list1').append(item);
}

演示:Fiddle