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

问题描述 投票:37回答:9

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

喜欢

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

我试过qazxsw poi ..(Javascript和jQuery)没有成功任何想法?

javascript jquery attributes
9个回答
47
投票

不要在id中使用空格。

添加自定义属性会使您的HTML无效。使用.getAttribute() and attr()代替:

data-attributes

<strong id="the_id" data-original-title="I NEED THIS"> $('#the_id').data('original-title');


38
投票

将“id”更改为“the_id”。

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

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

16
投票

最佳使用方式如下:

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

3
投票
jQuery(this).attr('original-title');

1
投票

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

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

1
投票

如果必须在id中使用空格,请检索元素和属性值,如下所示:

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

对于自定义属性,最好使用HTML5 $('[id="the id"]').attr([some attribute string]); //or $('#the\\ id').attr([some attribute string]); 属性,它是向后兼容和标准化的。所以在你的情况下,例如:

data-[somelabel]

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



0
投票

以下是一个工作示例:

使用Javascript:

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

HTML:

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

0
投票

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

<strong id="the_id" original-title="I NEED THIS"></strong>
© www.soinside.com 2019 - 2024. All rights reserved.