Domanda

Given this markup:

<a data-foo="bar baz">Hello</a>

Is it possible to remove baz but keep bar, ideally without removing both then adding back bar.

The jQuery removeData method appears to remove the specified data attribute or all data attributes.

È stato utile?

Soluzione

You can do

 $('a').data('foo', $('a').data('foo').split(' ')[0])

Altri suggerimenti

I'm not really sure this is what you're looking for, but this may help

  1. First get the data-foo values

    var foo = $('a').data('foo')

  2. Split the foo string to an array

    var foos = []

    foos = foo.split(" ")

  3. Pick the items you want to keep (or remove the items you want to remove)

    var index = foos.indexOf("baz")

    foos.splice(index,1)

  4. Put the string back together with only the left foos

    var foo = foos.join(" ")

  5. Set the data-foo to the new filtered one

    $('a').data('foo',foo)

Assuming data is a space delimited string:

var data = $("a").data("foo");
data = (" " + data + " ").replace(" baz ", " ").replace(/^ | $/g, "");
$("a").data("foo", data);

This should work for foo baz, baz foo, foo baz bar, etc.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top