如果您在 HTML 中有一个常规链接,您可以使用 jQuery 的 attr
函数获取其 href 属性的值:
<a id="testLink" href="test/link.html">Test Link</a>`
>>> $('#testLink').attr('href');
testLink.html
例子:
但是,如果链接是使用 jQuery 创建的,那么在 IE 7 中,此函数会返回浏览器在您单击链接时将访问的绝对 URL(例如 https://stackoverflow.com/questions/ask/testLink.html),而不是href
属性的字面值。
例子:
我也尝试过 this
、this.href
和 this.getAttribute('href')
,它们都返回一个绝对网址。
有没有办法获取 IE 7 中 jQuery 创建的链接的 href
属性的字面值?
最佳答案
如果您以 jQuery 被迫使用 .innerHTML
的方式创建链接,它将无法正常工作并记录在:http://api.jquery.com/html/ (还有 http://api.jquery.com/jQuery/#creating-new-elements):
This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.
要修复它,请以不强制 jQuery 使用 .innerHTML
的方式创建链接:
$('#test').append( $("<a>", {href: "test/link.html", text: "Test Link"}));
关于javascript - 在 IE 7 中,如果链接是使用 jQuery 创建的,您如何获取链接的 href 属性的字面值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11283607/