문제

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.

도움이 되었습니까?

해결책

You can do

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top