You can do
$('a').data('foo', $('a').data('foo').split(' ')[0])
문제
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
First get the data-foo values
var foo = $('a').data('foo')
Split the foo
string to an array
var foos = []
foos = foo.split(" ")
Pick the items you want to keep (or remove the items you want to remove)
var index = foos.indexOf("baz")
foos.splice(index,1)
Put the string back together with only the left foos
var foo = foos.join(" ")
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.