使用 Javascript 或 Jquery 获取自定义属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12226311/
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-23 07:26:55  来源:igfitidea点击:

Get value of a Custom Attribute using Javascript or Jquery

javascriptjqueryattributes

提问by stiffle

How can I get the value of a custom attribute using javascript or jquery?

如何使用 javascript 或 jquery 获取自定义属性的值?

Like

喜欢

<strong id="the id" original-title="I NEED THIS">

I've tried with .getAttribute() and attr()..(Javascrupt & jQuery) without success any idea?

我试过.getAttribute() and attr()..(Javascrupt & jQuery) 没有成功任何想法?

回答by jinsky

Don't use space in id.

不要在 id 中使用空格。

And adding custom attributes make your html invalid. Use data-attributesinstead:

添加自定义属性会使您的 html 无效。使用data-attributes来代替:

<strong id="the_id" data-original-title="I NEED THIS">

$('#the_id').data('original-title');

http://jsbin.com/akoyut/2/edit

http://jsbin.com/akoyut/2/edit

回答by Adam Wolski

Change "the id" to "the_id".

将“id”更改为“the_id”。

You can do it using plain javascript:

您可以使用普通的 javascript 来做到这一点:

document.getElementById("the_id").getAttribute("original-title");

回答by Sumit

Best Way to use like this:

像这样使用的最佳方式:

jQuery(this).attr('original-title');

回答by azmul

a var DateofEvent = $('[data-original-title=I NEED THIS]').val();

回答by Codegiant

You can get the value by using the following syntax

您可以使用以下语法获取值

$('#theid').attr('original-title');

回答by KooiInc

If you mustuse spaces in an id, retrieve the element and attribute value like this:

如果必须在 id 中使用空格,请像这样检索元素和属性值:

$('[id="the id"]').attr([some attribute string]);
//or
$('#the\ id').attr([some attribute string]);

For custom attributes best use the HTML5 data-[somelabel]attributes, it's backward compatible and standardized. So in your case something like:

对于自定义属性,最好使用 HTML5data-[somelabel]属性,它是向后兼容和标准化的。所以在你的情况下是这样的:

<strong id="the id" data-originalTitle="I NEED THIS">

Read more about data-attributes

阅读有关数据属性的更多信息

回答by coolguy

$('#the<remove space from here>id').attr('original-title');

回答by Mahbub

The following is an working example:

以下是一个工作示例:

Javascript:

Javascript:

$(document).ready(function() {    
  var title = $("#the_id").attr("original-title");
}

Html:

网址:

<strong id="the_id" original-title="I NEED THIS"></strong>

回答by Brainmaniac

I did this as I needed it in a foreach

我这样做是因为我在 foreach 中需要它

$(this).data('original-title')