ProgramingTip

데이터 ID 속성을 얻는 방법은 무엇입니까?

bestdevel 2020. 9. 29. 08:14
반응형

데이터 ID 속성을 얻는 방법은 무엇입니까?


jQuery Quicksand를 사용하고 있습니다. 클릭 한 항목의 데이터 ID를 가져 오기 웹 서비스에 전달해야합니다. 데이터 ID 속성은 어떻게 얻습니까? .on()정렬 된 항목에 대한 클릭 이벤트를 다시 바인딩 하는 방법을 사용하고 있습니다.

$("#list li").on('click', function() {
  //  ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
  alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<ul id="list" class="grid">
  <li data-id="id-40" class="win">
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
    </a>
  </li>
</ul>


속성 data-id(예 :)의 내용을 얻으려면 다음 <a data-id="123">link</a>을받을 수 있습니다.

$(this).attr("data-id") // will return the string "123"

또는 (최신 jQuery> = 1.4.3을 사용하는 경우).data()

$(this).data("id") // will return the number 123

다음 부분 data-은 소문자 택합니다. 예를 들어 data-idNum작동하지 않지만 작동 data-idnum합니다.


기존의 기본 JavaScript를 사용하여 기존 속성을 검색하거나 업데이트하고 같이 getAttribute 및 setAttribute 메소드를 사용하면됩니다.

JavaScript를 통해

<div id='strawberry-plant' data-fruit='12'></div>

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

jQuery를 통해

// Fetching data
var fruitCount = $(this).data('fruit');
OR 
// If you updated the value, you will need to use below code to fetch new value 
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).attr('data-fruit','7');

이 문서 읽기


중요 사항. JavaScript를 통해 data- 속성을 동적으로 조정 하면 data()jQuery 함수에 반영되지 않습니다 . data()기능을 통해서도 조정해야 합니다.

<a data-id="123">link</a>

js :

$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321

이전 IE 브라우저에 대해 걱정하지 않는다면 HTML5 데이터 세트 API를 사용할 수도 있습니다.

HTML

<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>

JS

var myDiv = document.querySelector('#my-div');

myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"

데모 : http://html5demos.com/dataset

전체 브라우저 지원 목록 : http://caniuse.com/#feat=dataset


아무도 언급하지 않았다는 것에 놀랐습니다.

<select id="selectVehicle">
     <option value="1" data-year="2011">Mazda</option>
     <option value="2" data-year="2015">Honda</option>
     <option value="3" data-year="2008">Mercedes</option>
     <option value="4" data-year="2005">Toyota</option>
    </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

다음은 작업 예제입니다 : https://jsfiddle.net/ed5axgvk/1/


HTML

<span id="spanTest" data-value="50">test</span>

JS

$(this).data().value;

또는

$("span#spanTest").data().value;

답변 : 50

나를 위해 작동합니다!


$ .data 사용-http: //api.jquery.com/jquery.data/

//Set value 7 to data-id 
$.data(this, 'id', 7);

//Get value from data-id
alert( $(this).data("id") ); // => outputs 7

var id = $(this).dataset.id

나를 위해 작동합니다!


자체 데이터 속성에 액세스하는 id것은 약간 쉽습니다.

$("#Id").data("attribute");

function myFunction(){
  alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>


이 코드는 데이터 속성의 값을 반환합니다. 예 : data-id, data-time, data-name 등.

<a href="#" id="click-demo" data-id="a1">Click</a>

js :

$(this).data("id");

// data-id 값 가져 오기-> a1

$(this).data("id", "a2");

// 이것은 데이터 ID를 변경합니다-> a2

$(this).data("id");

// data-id 값 가져 오기-> a2


jQuery 사용 :

  $( ".myClass" ).load(function() {
    var myId = $(this).data("id");
    $('.myClass').attr('id', myId);
  });

툴팁을 동적으로 제거하고 다시 활성화하려는 경우 disposeenable메서드를 사용할 수 있습니다 . https://getbootstrap.com/docs/4.0/components/tooltips/#tooltipdispose를 참조 하십시오.

참고 URL : https://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute

반응형