简体   繁体   中英

Jquery data-target as string possible?

I have a data-attribute with a unique name and a number at the end.

data-target="foo-bar-n"

where n is the unique number.

I want to be able to get that number but it isn't working.

I call:

.data("target")

on the object I want the target from and It returns fine, but when I use a regex search on the results, I get a completely different number, which I suspect is because returned data is an object with other data. What I need to know is how to get that number out, or how to convert the data-attribute into a string. (I've tried toString, and that doesn't work.)

Here is my code:

var selection= window.getSelection().getRangeAt(0);
var showSelection = $(selection.commonAncestorContainer.parentNode.parentNode)
  .data('target');
console.log(showSelection);
console.log(showSelection.search(/\d+/));

The console logs

#comment_for_paragraph_17
23

The program is meant to let a user select something on the page and highlight it.

If you are using jQuery 1.4.3 or later you can use

.data("target");

otherwise you must use

.attr("data-target");

But your requirement appears to be extracting a number from a formatted string parameter?

HTML:

<div id="foo" data-target="foo-bar-5"></div>

jQuery:

var num = $('#foo').data('target').split('-')[2];

Or regex:

var num = $('#foo').data('target').match(/\d+/);

Or if your requirement is specifically capture the last number in the string (eg: foo-bar-55-23 would result in '23')

var num = $('#foo').data('target').split('-').slice(-1);

// regex
var num = $('#foo').data('target').match(/\d+$/);

See fiddle

I suspect is because returned data is an object with other data.

That doesn't make any sense at all. The reason you are not getting the number in the string is because .search returns the index of the match. Use .match or .exec instead:

showSelection.match(/\d+/)[0];
          /*or*/
/\d+/.exec(showSelection)[0];

Try:

.data('target').split('-').slice(-1)[0];

.split will split your string into an array with each array element being a word

.slice(-1) will return an array consisting of the last element of your array

[0] accesses the array element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM