Javascript 向 Jquery 中的元素添加自定义属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8307635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:30:32  来源:igfitidea点击:

Add a custom attribute to an element in Jquery

javascriptjquery

提问by Sebastien

I'm trying to add a custom attribute on my element using jquery :

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

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

But in the end, my elements doesn't have a "element_id" attribute.

但最后,我的元素没有“element_id”属性。

PS, my html elements look like :

PS,我的 html 元素如下所示:

<div type="ground" class="map-areas-div" style="position: absolute; top: 900px; left: 720px; height: 40px; width: 90px;"></div>

Thank you for help

谢谢你的帮助

采纳答案by hungryMind

You can't. Use jQuery.data api instead to associate custom properties with element's jQuery wrapper. http://api.jquery.com/jQuery.data/

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

回答by JGilmartin

you can use jQuery .data() functionality.

您可以使用 jQuery .data() 功能。

var theDiv = $('#' + divID).data('winWidth', value);

Get the data back using

使用取回数据

theDiv.data('winWidth');

回答by Faron

I use the jQuery on-the-fly technique to accomplish that hack.

我使用 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);

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

回答by Amir Iqbal

You can add/set custom attribute in image also

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

var attr = 'data-img';
var img = 'Hello'
jQuery('img').attr(attr,img);

it will result

它会导致

<img src="xyz.jpg" data-img="Hello">

回答by Kemal Can Kara

First check

首先检查

$(this).css('background', 'url(' + randomItem.src + ')');

is working or not? If its working, put '' to your add attribute code like,

工作与否?如果它有效,请将 '' 添加到您的添加属性代码中,例如,

$(this).attr('element_id','4');