Jquery 停止函数在元素移动到另一个元素后影响该元素
因此,我必须创建html列表-一个用于选择,另一个用于添加Jquery 停止函数在元素移动到另一个元素后影响该元素,jquery,html,Jquery,Html,因此,我必须创建html列表-一个用于选择,另一个用于添加 <ul id="selet_from"> <li>1</li> <li>2</li> <li>3</li> </ul> <ul id="add_to"> </ul> 当我点击“从列表中选择”中的项目时,我需要添加一些文本并将其移动到“添加到列表” function add_to_selec
<ul id="selet_from">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul id="add_to">
</ul>
当我点击“从列表中选择”中的项目时,我需要添加一些文本并将其移动到“添加到列表”
function add_to_selected(){
$('#selet_from li:not(#add_to li)').click(function(){
//need to add text in child element for easy removal - works
$(this).html('<span>adittional text - </span>'+$(this).html());
// move element to 'selected' list
$(this).appendTo('#add_to');
// initialize remove from list on newly added items
remove_from_selected();
console.log('add')
});
};
到目前为止一切正常
如果我意外地将wrond项添加到列表中,那么我应该能够通过单击它来反转操作。也就是说,单击“添加到列表”中的项目应删除以前添加的文本,并将项目移回“从列表中选择”
function remove_from_selected(){
$('#add_to li').click(function(){
// need to remove <span child>
// example below doesn't work :(
$(this).remove('span');
// need to take element back to #selet_from
$(this).appendTo('#selet_from');
console.log('remove')
});
};
add_to_selected();
问题是,将元素移动到“添加到列表”后,不应执行“添加到选定的”函数,反之亦然 因为您正在寻找选择器的动态评估,所以请使用委托事件处理
$('#selet_from').on('click', 'li', function () {
//need to add text in child element for easy removal - works
$(this).html('<span>adittional text - </span>' + $(this).html());
// move element to 'selected' list
$(this).appendTo('#add_to');
});
$('#add_to').on('click', 'li', function () {
// need to remove <span child>
// example below doesn't work :(
$(this).children().remove();
// need to take element back to #selet_from
$(this).appendTo('#selet_from');
console.log('remove')
});
演示:Ohh,我明白了,不是直接将方法添加到要操作的对象,而是将方法添加到它们的容器中。哇,谢谢!