使用jQuery从分隔的列表中删除元素

时间:2015-07-06 17:49:09

标签: javascript jquery html

给定用逗号分隔的元素列表,如何使用jQuery或JS以通用方式删除一个元素和相关分隔符?

示例:

<div id="parent"><span name="one">one</span>,<span name="two">two</span>,
<span name="three">three</span>,<span name="four">four</span></div>

$("#parent").takeout("two")的结果将是:

<div id="parent"><span name="one">one</span>,
<span name="three">three</span>,<span name="four">four</span></div>

现在,$("#parent").takeout("one")的结果将是:

<div id="parent"><span name="three">three</span>,<span name="four">four</span></div>

$("#parent").takeout("four")的结果将是:

<div id="parent"><span name="three">three</span></div>

我想要一些通用的,可以使用任意数量的元素。

反向表示法(以span名称开头)也可以。

2 个答案:

答案 0 :(得分:2)

var name = 'one';
var $el = $('#parent > span[name="'+name+'"]')[0];
if($el.nextSibling !== null){
    $el.nextSibling.remove();
} else {
    if($el.previousSibling !== null)
        $el.previousSibling.remove();
}
$el.remove();

这有用吗?

答案 1 :(得分:0)

也许不是很漂亮,但它有效:

jQuery.prototype.takeout = function(id) {

    //Remove the span.
    jQuery("[name=" + id + "]", this).remove();

    //Save the HTML code of the parent.
    var code = this.html();

    //Remove any leading commas.
    code = code.replace(/(^\s*),/, "$1");

    //Remove any ending commas.
    code = code.replace(/,(\s*)$/, "$1")

    //Remove any double commas.
    code = code.replace(/,(\s*),/, ",$1")

    //Set the HTML.
    this.html(code);

    //Enable chaining.
    return this;

};

Working JSFiddle