說我有這樣的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