创建stackoverflow标记系统?

我正在尝试像SO一样创建一个标记系统。 我添加了标签,现在我想删除它们。

我的问题:

  • 如何删除附加的标签?
  • 如何使十字按钮(跨度)看起来与SO标记系统中的相同?

如此标记

var tags = []; $("#textBox").keypress(function (e) { if (e.which === 13) { $(".target").append("" + this.value+'X'+ ""); function remove_tag(){ //what to do here? } tags.push(this.value); this.value = ""; } }); 

这是我的JSFiddle: http : //jsfiddle.net/Wky2Z/11/

基本上,监听.cross被点击,然后从数组中 删除删除元素

 //enter something in textbox and press enter.... var tags = []; $("#textBox").keypress(function (e) { if (e.which === 13) { $(".target").append("" + this.value+'X'+ ""); tags.push(this.value); this.value = ""; } }); $('body').on('click','.cross',function(){ tags.splice($(this).parent('a').html(), 1); $(this).parent('a').remove(); }); 

至于十字架的外观,SO使用CSS Sprite,所以你可以通过制作两个状态的png或gif或jpeg,关闭(灰色)和hover(红色)并将background-position切换为红色来做同样的事情。用css例如: .cross:hover { background-position:0px -20px }

您可以删除使用remove()元素。 另外,我建议您使用jQuery事件而不是使用内联事件。 (如果你看一下stackoverflow的源代码,你会注意到没有内联的javascript调用)

在这种情况下,您需要向document对象添加事件处理程序,因为您希望将事件分配给从头开始未在DOM中加载的元素。

 $(document).on('click', '.tag span', function(){ $(this).parent().remove(); }); 

生活示例: http : //jsfiddle.net/Wky2Z/7/

更新

我更新了从标签列表中删除元素的示例: http : //jsfiddle.net/Wky2Z/8/

添加了标记链接的data-value

 $(".target").append("" + this.value+'X'+ ""); 

并修改了click事件:

 $(document).on('click', '.tag span', function(){ $(this).parent().remove(); var removeItem = $(this).parent().data('value'); tags = $.grep(tags, function(value) { return value != removeItem; }); }); 

对于完整的jQuery解决方案,您可以删除内联remove_tag函数并on函数on使用jQuery。 它也适用于动态创建的元素。

将一个或多个事件的事件处理函数附加到所选元素。

在这里,您可以获取已删除元素的父元素,并使用remove从DOM中remove

要使数组与当前情况“同步”,您可以使用grep从数组中删除该项; 请注意removedItem变量,用于仅获取父文本,不包括文本中的子项。

码:

 //enter something in textbox and press enter.... var tags = []; $(document).ready(function () { $('body').on('click', 'span.cross', function () { var removedItem = $(this).parent().contents(':not(span)').text(); $(this).parent().remove(); tags = $.grep(tags, function (value) { return value != removedItem; }); }); $("#textBox").keypress(function (e) { if (e.which === 13) { $(".target").append("" + this.value + 'X' + ""); tags.push(this.value); this.value = ""; } }); }); 

演示: http : //jsfiddle.net/IrvinDominin/pDFnG/

这是更新后的链接: http : //jsfiddle.net/Wky2Z/6/

remove_tag移动到remove_tag事件句柄之外,并将this指针传递给它以便快速解决:

 //enter something in textbox and press enter.... var tags = []; function remove_tag(x) { $(x).parent('a').remove(); } $(function () { $("#textBox").keypress(function (e) { if (e.which === 13) { $(".target").append("" + this.value + 'X' + ""); tags.push(this.value); this.value = ""; } }); });