我正在尝试在网站中执行标签过滤功能。从一个 div 转移到另一个 div 是有效的。但转回来就不行了。
这是我的 html:
<h4>Video Tags</h4>
<div id="tagbox-1">
<span class="tag-filter">tag 1</span>
<span class="tag-filter">tag 2</span>
<span class="tag-filter">tag 3</span>
</div>
<h4>Video Filters</h4>
<div id="tagfilter-1">
</div>
然后这是我的 javascript/jquery:
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append($(tag_object)).fadeIn();
$(tag_object).remove();
}
$(document).ready(function(){
var stored_tag = [];
$('[id^="tagbox-"] > span').each(function(){
$(this).click(function(){
tag_ui_move(this,'div[id^="tagfilter-"]');
});
});
$('div[id^="tagfilter-"] > span').each(function(){
$(this).click(function(){
tag_ui_move(this,'div[id^="tagbox-"]');
});
});
});
这几乎是我的 html 和代码的要点。我简化了它,因为有更多的 tagbox- 和 tagfilter- div。
最佳答案
问题是 $('[id^="tagbox-"] > span')
选择当时标签框中存在的所有标签范围元素,然后将点击处理程序绑定(bind)到每个元素,将其移动到过滤器 div。然后$('div[id^="tagfilter-"] > span')
选择当时存在于过滤器 div 中的所有标记 span 元素,并且没有任何元素。因此没有绑定(bind)处理程序来将元素移回。
此外,无需使用 .each()
循环单独绑定(bind).click()
对于循环中的每个元素:您只需调用 .click()
直接将处理程序绑定(bind)到与您的选择器匹配的所有元素。
解决方案是使用委托(delegate)处理程序,您可以在其中使用 .on()
将单击绑定(bind)到父 div 元素,但提供辅助选择器,jQuery 将在单击事件发生时自动测试该选择器:
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append(tag_object).fadeIn();
//$(tag_object).remove(); <-- commented out: don't remove the element,
// because append *moves* it
}
$(document).ready(function(){
var stored_tag = [];
$('[id^="tagbox-"]').on('click', 'span.tag-filter', function(){
tag_ui_move(this,'div[id^="tagfilter-"]');
});
$('div[id^="tagfilter-"]').on('click', 'span', function(){
tag_ui_move(this,'div[id^="tagbox-"]');
});
});
这样,当单击'[id^="tagbox-"]'
内的任何元素时发生时,jQuery 测试目标元素是否与选择器 'span.tag-filter'
匹配。当且仅当它执行时,它才会调用您的处理函数。因此,即使元素在两个父 div 之间动态来回移动,点击也会对元素起作用。
关于javascript 传输和元素从 1 个 div 到另一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25696960/