etc./StackOverFlow

jQuery를 사용하여 요소의 ID를 어떻게 얻을 수 있습니까?

청렴결백한 만능 재주꾼 2022. 2. 24. 22:02
반응형

질문자 :fearofawhackplanet


<div id="test"></div> <script> $(document).ready(function() { alert($('#test').id); }); </script>

위의 방법이 작동하지 않는 이유는 무엇이며 어떻게 해야 합니까?



jQuery 방식:

 $('#test').attr('id')

귀하의 예에서 :

 $(document).ready(function() { console.log($('#test').attr('id')); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="test"></div>

또는 DOM을 통해:

 $('#test').get(0).id;

또는 :

 $('#test')[0].id;

JQuery 또는 심지어 $('#test')[0] $('#test').get(0) 을 사용하는 이유는 $('#test') 가 JQuery 선택기이고 array()를 반환하기 때문입니다. 기본 기능으로 단일 요소가 아닌 결과

jquery에서 DOM 선택기의 대안은 다음과 같습니다.

 $('#test').prop('id')

.attr()$('#test').prop('foo') 것은 지정된 DOM foo 속성을 가져 $('#test').attr('foo') 은 지정된 HTML foo 여기에서 차이점에 대한 자세한 내용을 찾을 수 있습니다.


instanceof me

$('selector').attr('id') 는 첫 번째 일치 요소의 ID를 반환합니다. 참조 .

일치하는 세트가 둘 이상의 요소를 포함하는 경우 기존의 .each 반복자 를 사용하여 각 ID를 포함하는 배열을 반환할 수 있습니다.

 var retval = [] $('selector').each(function(){ retval.push($(this).attr('id')) }) return retval

또는 좀 더 거친 느낌을 주고 싶다면 래퍼를 피하고 .map 바로 가기를 사용할 수 있습니다.

 return $('.selector').map(function(index,dom){return dom.id})

Steven

id Element 의 속성입니다. $("#something") 을 작성하면 일치하는 DOM 요소를 래핑하는 jQuery 객체가 반환됩니다. 일치하는 첫 번째 DOM 요소를 다시 get(0)

 $("#test").get(0)

이 기본 요소에서 id 또는 다른 모든 기본 DOM 속성이나 함수를 호출할 수 있습니다.

 $("#test").get(0).id

이것이 id 가 코드에서 작동하지 않는 이유입니다.

또는 jQuery의 attr 메서드를 사용하여 첫 번째 일치 요소 id 속성을 가져오도록 제안합니다.

 $("#test").attr("id")

Anurag

위의 답변은 훌륭하지만 jquery가 발전함에 따라 다음과 같이 할 수도 있습니다.

 var myId = $("#test").prop("id");

Chris

$.fn.extend({ id : function() { return this.attr('id'); } }); alert( $('#element').id() );

물론 몇 가지 검사 코드가 필요하지만 쉽게 구현됩니다!


stat

.id 는 유효한 jquery 함수가 아닙니다. 요소가 소유한 속성에 액세스하려면 .attr() .attr() 을 사용하여 두 개의 매개변수를 지정하여 속성 값을 변경하거나 하나를 지정하여 값을 가져올 수 있습니다.

http://api.jquery.com/attr/


Joey C.

특정 요소에서 이벤트(이 경우 클릭 이벤트)가 발생했을 때 클래스 선택기를 사용하여 요소의 ID를 얻으려면 다음이 작업을 수행합니다.

 $('.your-selector').click(function(){ var id = $(this).attr('id'); });

Jay Query

$('#test').attr('id') 귀하의 예에서 :

 <div id="test"></div> $(document).ready(function() { alert($('#test').attr('id')); });

Kumar

글쎄요, 솔루션이 없는 것 같으며 JQuery 프로토타입의 확장인 나만의 솔루션을 제안하고 싶습니다. JQuery 라이브러리 다음에 로드되는 도우미 파일에 이것을 넣었으므로 window.jQuery

 if (window.jQuery) { $.prototype.id = function () { if (this.length > 1) { var val = []; this.each(function (idx, el) { val.push($(el).id()); }); return val; } else { return this.attr('id'); } } }

완벽하지는 않지만 JQuery 라이브러리에 포함되기 시작하는 단계입니다.

단일 문자열 값 또는 문자열 값의 배열을 반환합니다. 문자열 값의 배열은 다중 요소 선택기가 사용된 이벤트용입니다.


GoldBishop

$('#test') 는 jQuery 개체를 반환하므로 단순히 object.id 를 사용하여 해당 Id

요소 ID 를 반환하는 $('#test').attr('id') 사용해야 합니다.

이것은 또한 다음과 같이 수행할 수 있습니다.

$('#test').get(0).iddocument.getElementById('test').id


user372551

이 스레드를 찾는 다른 사람들에게 유용할 수 있습니다. 아래 코드는 이미 jQuery를 사용하는 경우에만 작동합니다. 함수는 항상 식별자를 반환합니다. 요소에 식별자가 없으면 함수는 식별자를 생성하고 이를 요소에 추가합니다.

 var generatedIdCounter = 0; $.fn.id = function() { var identifier = this.attr('id'); if(!identifier) { generatedIdCounter++; identifier = 'isGenerated_' + generatedIdCounter; this.attr('id', identifier); } return identifier; }

사용하는 방법:

 $('.classname').id(); $('#elementId').id();

Tom

$('tagname').attr('id');

위의 코드를 사용하면 id를 얻을 수 있습니다.


JayminLimbachiya

이것은 오래된 질문 이지만 2015년 현재 이것은 실제로 작동할 수 있습니다.

 $('#test').id;

또한 다음과 같이 할당할 수도 있습니다.

 $('#test').id = "abc";

다음 JQuery 플러그인을 정의하는 한:

 Object.defineProperty($.fn, 'id', { get: function () { return this.attr("id"); }, set: function (newValue) { this.attr("id", newValue); } });

흥미롭게도 element 가 DOM 요소인 경우:

 element.id === $(element).id; // Is true!

MarcG

id attr 메소드를 사용하여 얻을 수 있습니다.


Oussidi Mohamed

이것은 요소 id , class , 또는 even을 사용하여 자동으로 될 수 있습니다.

 ------------------------ $(this).attr('id'); ========================= ------------------------ $("a.remove[data-id='2']").attr('id'); ========================= ------------------------ $("#abc1'").attr('id'); =========================

Daniel Adenew

이것은 마침내 당신의 문제를 해결할 것입니다:

페이지에 많은 버튼이 있고 그 중 하나를 ID에 따라 jQuery Ajax(또는 ajax 아님)로 변경하고 싶다고 가정해 보겠습니다.

또한 다양한 유형의 버튼(양식, 승인 및 유사한 목적)이 있고 jQuery가 "좋아요" 버튼만 처리하기를 원한다고 가정해 보겠습니다.

작동하는 코드는 다음과 같습니다. jQuery는 .cls-hlpb 클래스의 버튼만 처리하고, 클릭된 버튼의 ID를 가져와서 ajax에서 가져온 데이터에 따라 변경합니다.

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> <script> $(document).ready(function(){ $(".clshlpbtn").on('click',function(e){ var id = $(e.target).attr('id'); alert("The id of the button that was clicked: "+id); $.post("demo_test_post.asp", { name: "Donald Duck", city: "Duckburg" }, function(data,status){ //parsing the data should come here: //var obj = jQuery.parseJSON(data); //$("#"+id).val(obj.name); //etc. if (id=="btnhlp-1") $("#"+id).attr("style","color:red"); $("#"+id).val(data); }); }); }); </script> </head> <body> <input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn"> </input> <br /> <input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn"> </input> <br /> <input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn"> </input> </body> </html>

코드는 w3schools에서 가져와 변경되었습니다.


user3495363

중요: jQuery로 새 객체를 만들고 이벤트를 바인딩하는 경우 다음과 같이 attr 이 아닌 prop 을 사용해야 합니다.

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");


Camila S.

<html> <head> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <?php // include Database connection file include("db_connection.php"); // Design initial table header $data = '<table class="table table-bordered table-striped"> <tr> <th>No.</th> <th>First Name</th> <th>Last Name</th> <th>Email Address</th> <th>Update</th> <th>Delete</th> </tr>'; $query = "SELECT * FROM users"; if (!$result = mysqli_query($con, $query)) { exit(mysqli_error($con)); } // if query results contains rows then featch those rows if(mysqli_num_rows($result) > 0) { $number = 1; while($row = mysqli_fetch_assoc($result)) { $data .= '<tr> <td>'.$number.'</td> <td>'.$row['first_name'].'</td> <td>'.$row['last_name'].'</td> <td>'.$row['email'].'</td> <td><button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button> </td> </tr>'; $number++; } } else { // records now found $data .= '<tr><td colspan="6">Records not found!</td></tr>'; } $data .= '</table>'; echo $data; ?> <script type="text/javascript"> function DeleteUser(id) { var conf = confirm("Are you sure, do you really want to delete User?"); if (conf == true) { $.ajax({ url:'deleteUser.php', method:'POST', data:{ id:id }, success:function(data){ alert('delete successfully'); } } }); deleteUser.php <?php // check request if(isset($_POST['id']) && isset($_POST['id']) != "") { // include Database connection file include("db_connection.php"); // get user id $user_id = $_POST['id']; // delete User $query = "DELETE FROM users WHERE id = '$user_id'"; if (!$result = mysqli_query($con, $query)) { exit(mysqli_error($con)); } } ?>

Himani

OP에 응답하지 않지만 다른 사람들에게 흥미로울 수 있습니다. 이 경우 .id

 $('#drop-insert').map((i, o) => o.id)

mariotomo

출처 : http:www.stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery

반응형