说我有这样的HTML代码:jQuery的获取属性和元素的值
<img id="idgoeshere" src="srcgoeshere" otherproperty="value" />
我可以通过它的id引用元素:$('#idgoeshere'))
现在,我想该元素的所有属性和它们的值:
src=srcgoeshere
otherproperty=value
有没有什么办法可以通过编程方式使用jQuery和/或纯Javascript?
说我有这样的HTML代码:jQuery的获取属性和元素的值
<img id="idgoeshere" src="srcgoeshere" otherproperty="value" />
我可以通过它的id引用元素:$('#idgoeshere'))
现在,我想该元素的所有属性和它们的值:
src=srcgoeshere
otherproperty=value
有没有什么办法可以通过编程方式使用jQuery和/或纯Javascript?
您可以通过检查属性属性得到的列表:
var attributes = document.getElementById('idgoeshere').attributes;
// OR
var attributes = $('#idgoeshere')[0].attributes;
alert(attributes[0].name);
alert(attributes[0].value);
$(attributes).each(function()
{
// Loop over each attribute
});
我想他想列出所有的属性,而不是一些具体的属性。 – 2011-04-07 15:37:03
是的,你可以!
的Jquery:
var src = $('#idgoeshere').attr('src');
var otherproperty = $('#idgoeshere').attr('otherproperty');
的Javascript:
var src = document.getElementById('idgoeshere').getAttribute('src');
var otherproperty = document.getElementById('idgoeshere').getAttribute('otherproperty');
您还可以设置属性: – 2011-04-07 15:37:09
$('#idgoeshere')。attr('src','myimage.jpg'); – 2011-04-07 15:37:39
您可以使用该attr
:
对于如。
var mySrc = $('#idgoeshere').attr("src");
var otherProp = $('#idgoeshere').attr("otherproperty");
如果你只想得到所有属性的列表,请参阅这个问题的答案:Get all Attributes from a HTML element with Javascript/jQuery
试试这个:
var element = $("#idgoeshere");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
请注意,一个元素的属性与元素的属性不同。 – Flimm 2015-06-12 09:15:25