简体   繁体   English

我如何使用jQuery获取div中的属性

[英]how can i get attribute in div with jquery

this is code from firebug, i want to get data-name value 这是firebug的代码,我想获取数据名称值

<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 我如何通过单击jQuery获取属性数据名称

You can use data . 您可以使用data

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

To get the data-name of the clicked image. 获取单击图像的data-name

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

Demo: https://jsfiddle.net/tusharj/a0468f8k/ 演示: 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/ 文件: http//api.jquery.com/data/

I'm assuming clicked on img itself, then try this code : 我假设点击了img本身,然后尝试下面的代码:

$(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/ http://jsfiddle.net/re1Lz451/1/

By use of jQuery library data can be fetch easily, there is a method data() apply on object. 通过使用jQuery库,可以轻松获取数据,有一种方法data()应用于对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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