Javascript:setAttribute 有效,getAttribute 失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19960537/
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
Javascript: setAttribute works, getAttribute fails
提问by varrtto
I have this code:
我有这个代码:
var object1 = getElementByID('obj1');
alert(object1.getAttribute('href'));
This displays correctly the URL in the href attribute of the object. But, when I try:
这将正确显示对象的 href 属性中的 URL。但是,当我尝试:
var object1 = getElementByID('obj1');
object1.setAttribute('href','someotherURL');
alert(object1.getAttribute('href'));
This fails. The code doesn't work on FF so I can only test it in IE, no Firebug =/. I have also tried.
这失败了。代码在 FF 上不起作用,所以我只能在 IE 中测试它,没有 Firebug =/。我也试过了。
object1.href = "someotherURL";
but it also fails. Does anyone knows why I cant modify the attribute? let me know if I need to provide more information.
但它也失败了。有谁知道为什么我不能修改属性?如果我需要提供更多信息,请告诉我。
Regards.
问候。
UPDATE: HTML:
更新:HTML:
<table class="msrs-topBreadcrumb" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td>
<span>
<div>
<a href="SomeURL">A Name</a> >
<a href="AnotherURL">A Name2</a> >
<a href="Third URL">A Name3</a>
</div>
</span>
</td>
<td align="right">
<span>
<a href="URL1">A Name</a> |
<a href="URL2">A Name2</a> |
<a href="URL3">A Name3</a> |
<a href="URL4">A Name4</a>
</span>
</td>
</tr>
</table>
FUNCTION:
功能:
function mySubscriptions()
{
var mySubsObj = getElementsByClass('msrs-topBreadcrumb')[0].firstChild.childNodes[0].childNodes[1].childNodes[0].childNodes[2];
alert(mySubsObj.getAttribute("href"));
}
回答by Guffa
Use document.getElementById
and it works fine:
使用document.getElementById
它工作正常:
var object1 = document.getElementById('obj1');
object1.setAttribute('href','someotherURL');
alert(object1.getAttribute('href'));
Tested in Firefox, IE and Chrome.
在 Firefox、IE 和 Chrome 中测试。