Cross-browser change an A tags' HREF

筅森魡賤 提交于 2019-12-11 23:51:38

问题


it seems I can not find document.getElementById().href in the Javascript reference, there are a lot of sites saying to use this to change the href of a link. Is this safe? Will it work in all browsers? Or should I just already have my other link ready and replace the old one when it is no longer needed?

I only have 2 possible values I will for the link, depending on the last action performed by the user, either "delete" or "revive". So I guess replacing the link rather than changing it would not be much of a burden. I would rather change it if it will work in all browsers though.

Thanks


回答1:


You can't find it in any reference, as it's not a single construct, it's the combination of two.

Use the document.getElementById method to get a specific element, and if that element is an anchor tag, you can use the href property to set the URL.

Both are specified in the DOM level 1 specification, so they are safe to use in any browser that isn't more than a decade old, and most that are a bit older too.




回答2:


Guffa is correct. See:

https://developer.mozilla.org/en/DOM/HTMLAnchorElement

and

https://developer.mozilla.org/en/DOM/document.getElementById




回答3:


I am fairly sure it is "safe" nothing bad will happen. It works in all browser I have tested it in, and is the standard in which JavaScript changes the values of elements attributes.




回答4:


I have asked a similar question here: Retrieving HTML attribute values "the DOM 0 way"

Check out the answers. The conclusion is that the attributes src, href and style are not safe and a JavaScript library is recommended.

For the href attribute, I recommend jQuerys attr() method.

// retrieve the anchor by ID
var anchor = $('#anchorID');

// get the href attribute
var href = anchor.attr('href');

// set the href attribute
anchor.attr('href', 'http://www.google.com');


来源:https://stackoverflow.com/questions/4632091/cross-browser-change-an-a-tags-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!