programing

jQuery를 사용하여 요소의 ID를 얻으려면 어떻게 해야 합니까?

showcode 2023. 5. 25. 22:13
반응형

jQuery를 사용하여 요소의 ID를 얻으려면 어떻게 해야 합니까?

<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;

사배 및이유의 $('#test').get(0) 또는 JQuery에서도.$('#test')[0]은 것은입니다.$('#test')JQuery 선택기이며 기본 기능으로 단일 요소가 아닌 결과 배열()을 반환합니다.

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

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

과 것.attr()그리고.$('#test').prop('foo')된 DOM 지된DOM 가옵니다져을정을 붙잡습니다.foo에 성속, 면반$('#test').attr('foo')된 HTML 지된을HTML 가져니를 .foo여기에서 차이점에 대한 자세한 내용을 확인할 수 있습니다.

$('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})

id입니다.Element, 만지하를 쓸 당이글쓸때을신쓸때▁however.$("#something")일치하는 DOM 요소를 래핑하는 jQuery 개체를 반환합니다.다시 , "DOM 요소"를 합니다.get(0)

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

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

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

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

의 "jQuery"를 합니다.attr다른 답변이 제안하는 방법은 다음과 같습니다.id첫 번째 일치 요소의 속성입니다.

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

위의 답변은 좋지만, jquery가 발전함에 따라..따라서 다음 작업도 수행할 수 있습니다.

var myId = $("#test").prop("id");
$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

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

.id올바른 jquery 함수가 아닙니다.은 사을용합니다야를 해야 합니다..attr()요소가 소유한 속성에 액세스하는 함수입니다.사용할 수 있습니다..attr()두 매개 변수를 지정하여 속성 값을 변경하거나 하나를 지정하여 값을 가져옵니다.

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

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

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

$('#test').attr('id')예를 들어, 다음과 같습니다.

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

글쎄요, 아직 해결책이 없는 것 같습니다. JQuery 시제품의 확장인 저만의 해결책을 제안하고 싶습니다. 라이브러리 되는 Helper 에 Helper 파일을 합니다.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 라이브러리에 포함되는 것이 시작일 수 있습니다.

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

$('#test')jQuery 개체를 반환하므로 단순하게 사용할 수 없습니다.object.id그것을 얻기 위해Id

사용해야 합니다.$('#test').attr('id')그러면 필요한 항목이 반환됩니다.ID기본적인

이는 또한 다음과 같이 수행될 수 있습니다.

$('#test').get(0).id와 같은 것document.getElementById('test').id

    $("#button").click(function() {
      var clickID = $("#testDiv").attr("id");
      console.log(clickID)
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="testDiv"> When button will click you'll get this id value </div>
<button id="button"> Button </button>

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

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

이 스레드를 찾는 다른 사람들에게 유용할 수 있습니다.아래 코드는 이미 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();

이것은 오래된 질문이지만, 2015년 기준으로 실제로 효과가 있을 수 있습니다.

$('#test').id;

또한 다음과 같이 할당할 수:

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

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

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

흥미롭게도, 만약에elementDOM 요소이며, 다음과 같습니다.

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

id는 속성이므로 다음을 사용하여 얻을 수 있습니다.attr방법.

요소 ID, 클래스 또는 자동으로 짝수를 사용할 수 있습니다.

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

이렇게 하면 마침내 문제가 해결됩니다.

페이지에 많은 단추가 있고 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>

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

<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));
    }
}
?>

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

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

그것은 OP에 대답하지 않지만, 다른 사람들에게는 흥미로울 수 있습니다: 당신은 접근할 수 있습니다..id이 경우 필드:

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

언급URL : https://stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery

반응형