在Jquery中为元素添加自定义属性

Seb*_*ien 16 javascript jquery

我正在尝试使用jquery在我的元素上添加自定义属性:

$('.map-areas-div').rand(numElements).each(function(){
      $(this).attr('element_id',4);
});
Run Code Online (Sandbox Code Playgroud)

但最后,我的元素没有"element_id"属性.

PS,我的html元素看起来像:

<div type="ground" class="map-areas-div" style="position: absolute; top: 900px; left: 720px; height: 40px; width: 90px;"></div>
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

JGi*_*tin 14

你可以使用jQuery .data()功能.

var theDiv = $('#' + divID).data('winWidth', value);
Run Code Online (Sandbox Code Playgroud)

使用获取数据

theDiv.data('winWidth');
Run Code Online (Sandbox Code Playgroud)


Far*_*ron 10

我使用jQuery on-the-fly技术来完成这个hack.

$(document).ready(function() {

  $('<div>').attr('id', 'attributename').attr('faron', 'Idunnoyoucanseeme').text('Hello, I am the element with made-up attribute built on the fly.  Made up attribute: faron').appendTo('#nest');

  var attributegrabber = $('#attributename').attr('faron');

  alert(attributegrabber);

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nest"></div>
Run Code Online (Sandbox Code Playgroud)

  • 这适用于基本类型,但不适用于复杂类型(函数,对象文字等).数据属性方法适用于两者. (2认同)

hun*_*ind 7

你不能.使用jQuery.data api来将自定义属性与元素的jQuery包装器相关联.http://api.jquery.com/jQuery.data/


小智 5

您也可以在图像中添加/设置自定义属性

var attr = 'data-img';
var img = 'Hello'
jQuery('img').attr(attr,img);
Run Code Online (Sandbox Code Playgroud)

它会导致

<img src="xyz.jpg" data-img="Hello">
Run Code Online (Sandbox Code Playgroud)