Jquery 를 사용하여 요소의 id 를 어떻게 해야 할까요?

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

왜, 어떻게 해야 하나요, t # 39 위 작동합니까 doesn& 이?

질문에 대한 의견 (1)
해결책

방법을 포함한다.

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

In your 예:

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

$(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>

끝 - &lt 스니핏 >;!

통해 또는 DOM:

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

심지어:

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

뒤에 사용 및 사유 (& # 39, # test& # 39;) '$ 이제 (0)' 에서 '$ (& # 39, # test& # 39,) 또는 심지어 JQuery [0]' 에로남이네 (& # 39, # test& # 39;) '은' $ JQuery 선택기를 어레이에서는 되돌려줍니다 및 하나도 없는 결과 () 은 기본 기능을 통해 요소를

jquery 는 DOM 선택기의 위한 대안을

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

이는 스타르 () '와' 다르다 '$ (& # 39, # test& # 39;) 지프로프 (& # 39, foo& # 39;)', '속성' 동시에 '여기서 지정된 DOM foo $ (& # 39, # test& # 39;) 스타르 (& # 39, foo& # 39;)' 'foo' 속성과 지정된 HTML 잡습니다 변경분 here 대한 자세한 내용을 확인할 수 있습니다.

해설 (20)

'$ (& # 39, selector& # 39;) 스타르 (& # 39, id& # 39;)' 의 id 를 반환되므로 첫 번째 매칭됨 요소. 참고.

둘 이상의 요소를 정합된 세트에는 경우 기존 '그레이크 사용할 수 있습니다' 반복자가 반환되기를 redboot*용 어레이에서는 각 id:

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

39, re 기꺼이 you& 경우에는 조금 크리스티에 래퍼 및 사용할 수 있습니다 '오마프 피할 수 있는' 짧은보기.

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

html 요소 '' 'id' 의 속성입니다. 그러나 작성할 때 ',' $ (&quot, # something") 이 일치하는 DOM element (s) 는 객체 둘러싸여집니다 되돌려줍니다 포함한다. 첫 번째 일치하는 DOM element (0) '' afaq 뒤로를 호출하십시오 확보하십시오.

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

여기있을 콜러 id 기능을 기본 요소, 또는 다른 모든 기본 DOM 속성 또는 수 있습니다.

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

39 의 that& 'id' isn& 코드에서 # 39, apc® 이유가 없다.

39 의 '속성' 사용 또는 다른 방법으로 답을 얻기 위해 제안하세요 jQuery& 'id' 특성에 맞는 첫 번째 요소입니다.

$("#test").attr("id")
해설 (0)

그러나 위 대답이 멋지구리해요 jquery 발전합니다. 그렇게 할 수도 있습니다.

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

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

물론, 그 일부 필수 체크 코드를 쉽게 구축됩니까!

해설 (1)

id 유효하지 않은 '' 기능을 포함한다. '특성에 액세스하려면 스타르 ()' 기능을 사용하는 데 필요한 요소를 갖추고 있다. '스타르 ()' 을 모두 지정하여 사용할 수 있는 속성 값 변경 또는 두 개의 매개 변수 값을 얻을 불신하니 지정하여

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

해설 (0)

39 이라는 ID afaq 스케쳐내 요소를 let&, s 클래스에 의해서 말하도다 선택기를 이벤트로 (이 경우 클릭 이벤트) 는 특정 요소에 대한 해고, 다음 작업을 수행할 수 있는 것이다.

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

뭐, 좁히어 솔루션과 않은 것 같다 싶은 나만의 제안하십시오 솔루션입니다 prototype& # 39 의 확장으로 포함한다. I put 이 파일을 한 후, 즉 '도우미' 확인할지 빈다우.j케리 로드되었는지 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');
        }
    }
}

완벽한 것은 아마도 시작 할 수 없습니다 포함인지 꽂으십시오 라이브러리를 포함한다.

하나의 문자열 값이거나 인컨텍스트 되돌려줍니다 배열입니다 구체화하십시오 값. 배열에 구체화하십시오 값뿐만 캐비닛용입니다 이벤트 오버클로킹된 다중 요소 선택기를 사용했다.

해설 (0)

'$ (& # 39, # test& # 39;)' 가 'object.id', jQuery 객체를 사용할 수 있도록 can& t # 39 는 단순히 'Id'

사용해야 할 때 '$ (& # 39, # test& # 39;) 스타르 (# 39, & # 39, id&)', '어떤 요구 사항을 되돌려줍니다 요소의 ID'

이 다음과 같이 수행할 수도 있습니다.

(# 39, & # 39, # test&) '$ 이제 .id (0)' 을 '도쿠망스게테레멘트베이드 (& # 39, test& # 39;)' 같은 .id

해설 (1)

'$ (& # 39, # test& # 39;) 스타르 (& # 39, id& # 39;)' In your 예:

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

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

아마 다른 찾을 때 유용하게 사용할 수 있는 이 어떨까. 아래 코드는 jQuery 이미 사용하고 있는 경우에만 사용할 수 있습니다. 이 함수는 항상 식별자입니다. # 39 요소점 doesn& 없는 경우, 함수 식별자입니다 생성하는지 식별자입니다 및 덮어쓰기/추가 이 요소.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use.

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

$('#elementId').id();
해설 (0)
$('tagname').attr('id');

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

해설 (0)

그러나 이것은 오래된 질문 , 작업 (2015년 기준) 이 있을 수 있습니다.

$('#test').id;

지정 및 할 수도 있습니다.

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

As long as you 정의하십시오 플러그인에는 다음을 포함한다:

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

흥미롭게도, 만약 '요소' 는 DOM element 후:

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

이 요소점 id, 클래스, 또는 사용하여 자동으로 할 수 있습니다.

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

, Id 는 이후 '속성' 방법을 사용하여 속성용 이해했소 수 있습니다.

해설 (0)

않니다 대답하지 않고 필요할 수 있지만, 다른 유명한 OP. id 액세스하려면 '현장' 이 경우:

"'javascript $ (& # 39, # drop-insert& # 39;) 오마프 ((i, o) = &gt. 오이드) "'

해설 (1)

중요: 새 객체를 생성하는 경우 제안 합니다 사용할 수 있는 이벤트가 jQuery 및 바인딩하면 아니라 다음과 같은 속성을 ,

'$ (,,, &quot &lt div/&gt &quot {id: yourid&quot ";, 클래스: &quot yourClass&quot html:;; ,, &quot &lt span&gt &lt /span&gt &quot. }) 오언 (&quot, click", 함수 (e) {경고 ($ (이) 지프로프 (id&quot ";)); }), '스타펀트로 (# something&quot ";)

해설 (0)

결국 이 문제 해결:

말할 수 있는 것인지 페이지에서든 곷떒 많이 보유하고 있는 afc 아약스 (방관하겠나 아약스) 를 따라 둘 중 하나를 변경하십시오 포함한다.

또한 말할 수 있는 다양한 유형의 단추 (대해 승인 및 양식의 경우, 같은 목적을 위해), 그리고 오직 &quot like&quot, 치료를 위해 운영까지도 포함한다. 버튼.

다음은 apc® 코드입니다. 만, 클래스 .cls-hlpb 않는비즈니스 곷떒 대해 줄지 포함한다 id 가 시행하십시오 버튼을 클릭하면 됩니다 ajax 의 자료에 따르면 주공은 변경하십시오 나오는 것입니다.





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



<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">            
해설 (0)



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

<?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>Delete
                </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));
    }
}
?>
해설 (0)