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

时间:2022-11-18 19:00:35

Given a list of elements separated by commas, how do I remove one element and the relevant separator, in a generic way, with jQuery or JS?

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

Example:

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

Result of $("#parent").takeout("two") would be:

$(“#parent”)。takeout(“two”)的结果将是:

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

Now, result of $("#parent").takeout("one") would be:

现在,$(“#parent”)。takeout(“one”)的结果将是:

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

And, result of $("#parent").takeout("four") would be:

并且,$(“#parent”)。takeout(“four”)的结果将是:

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

I would like something generic, that would work with any number of elements.

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

The reverse notation (starting with span name) would also work.

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

2 个解决方案

#1


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();

Does this work?

这有用吗?

#2


0  

Perhaps not very pretty, but it works:

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

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.

#1


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();

Does this work?

这有用吗?

#2


0  

Perhaps not very pretty, but it works:

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

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.