javascript - 在 IE 7 中,如果链接是使用 jQuery 创建的,您如何获取链接的 href 属性的字面值?

标签 javascript jquery internet-explorer-7

如果您在 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 属性的字面值。

例子:

我也尝试过 thisthis.hrefthis.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"}));

http://jsfiddle.net/xtrEB/12/

关于javascript - 在 IE 7 中,如果链接是使用 jQuery 创建的,您如何获取链接的 href 属性的字面值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11283607/

相关文章:

css - 我的页面布局在 IE7 中中断,如果我将鼠标悬停在/打开菜单项上,它会自行恢复

css - IE7 切断 span 标签上的边框

javascript - Angular.js 和 HTML/如何并排组合 2 个元素

javascript - 函数式编程的部分函数和全局作用域

javascript - 当文本框有效时隐藏弹出窗口

javascript - 在多个 Chosen Select 中隐藏选中的选项

javascript - 如何观察给div添加class

javascript - Quasar Q-Table 如何获得过滤或排序的行?

javascript - 使用javascript在aws上获取pdf的页数

html - 背景 CSS 图像仅在 IE7 中不显示