$('#button').click(function() {
parentID = $(this).parent().attr('id');
newID = +(parentID.match(/\d+/));
alert(newID);
});
Only get the number from parent id
-
14-10-2022 - |
문제
I want to get the id
from the parent element of a button, and the cut the text of. My guess was this:
HTML
<div id="test_4">
<button id="button">Get ID</button>
</div>
JavaScript
$('#button').click(function() {
parentID = $(this).parent().attr('id');
newID = parseInt(parentID);
alert(newID);
});
But that outputs NaN
.
What is the right way to do this? fiddle
해결책 2
다른 팁
There are many answers which use Regular Expressions but I don't recommend it. What you need is data-
attributes. You use jQuery already so you can access your id
with .data()
method. Here is an example;
HTML
<div id="test_4" data-id="4">
<!-- ^^^^^^^^^^^^ this has to be added to use .data() -->
<button id="button">Get ID</button>
</div>
JavaScript
$('#button').click(function() {
var newID = $(this).parent().data('id');
alert(newID);
});
Use a simple regex
$('#button').click(function () {
var parentID = $(this).parent().attr('id');
var newID = parentID.match(/\d+$/)[0];
alert(newID);
});
Demo: Fiddle
You can use regex to match the number inside your id
string:
parentID = $(this).parent().attr('id').match(/\d+/);
Try this :
$('#button').click(function() {
parentID = $(this).parent().attr('id');
newID = parseInt(parentID.split("_")[1]);
alert(newID);
});
Demo : http://jsfiddle.net/3FZya/6/
$('#button').click(function() {
parentID = $(this).parent().attr("id");
newID = parentID;
alert(newID);
});
this will work
제휴하지 않습니다 StackOverflow