简体   繁体   中英

how can i get attribute in div with jquery

this is code from firebug, i want to get data-name value

<div id="listdata">
     name1
      <img src="images1" data-name="data01">
     name2
      <img src="images2" data-name="data02">
     name3
      <img src="images2" data-name="data03">

how can i get attribute data-name by click with Jquery

You can use data .

$('#images1').data('name');

To get the data-name of the clicked image.

$(document).ready(function () {
    $('#listdata').on('click', 'img', function () {
        alert($(this).data('name'));
    });
});

Demo: https://jsfiddle.net/tusharj/a0468f8k/

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

Docs: http://api.jquery.com/data/

I'm assuming clicked on img itself, then try this code :

$(function(){
  $('#listdata').on('click','img', function(){
    alert($(this).data('name'));
  });
});
<div id="listdata">
     name1
    <img src="images1" data-name="data01" />
     name2
    <img src="images2" data-name="data02" />
     name3
    <img src="images2" data-name="data03" />
</div>




$("#listdata img").click(function(){
    console.log($(this).data("name"));
});

http://jsfiddle.net/re1Lz451/1/

By use of jQuery library data can be fetch easily, there is a method data() apply on object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM