IE7中的.attr(“href”)错误提取与所有其他浏览器相比?

时间:2009-10-20 08:29:51

标签: jquery internet-explorer-7 relative-path href absolute-path

与其他所有浏览器相比,IE7中链接的attr("href")命令处理方式是否真的如此?

假设我在http://example.com/page.html有一个页面,我有这个HTML:

<a href="#someAnchor" class="lnkTest">Link text</a>

和这个jQuery:

var strHref = $(".lnkTest").attr("href");

然后在IE7中,strHref变量的值将为"http://example.com/page.htm#someAnchor",但在其他浏览器中,它将为"#someAnchor"

我相信最后提到的案例是最正确的案例,所以它只是一个IE7是一个坏男孩的案例,还是jQuery中的一个错误?

7 个答案:

答案 0 :(得分:18)

肯定不是 jQuery中的错误,而是浏览器.getAttribute('href')的不一致实现 - 我建议只使用.get(0).href来保持一致性。

如果您不想使用绝对URI,似乎可以使用.get(0).getAttribute('href', 2)访问IE和Mozilla中的属性文本。但请注意,这在Opera中不起作用,我还没有在Safari / Chrome /其他任何地方进行过测试。

你也可以删除域名或拆分.get(0).href的'#'并使用数组的第二部分,假设它甚至包含'#'(检查.length)。

http://www.glennjones.net/Post/809/getAttributehrefbug.htm

答案 1 :(得分:4)

我相信它在所有IE 7 +中都是这样实现的。

我用:

var href=jQuery('#foo').attr('href');
href=href.substring(href.indexOf('#'));

希望它有所帮助! 欢呼声。

答案 2 :(得分:2)

我发现了与此问题相关的错误:http://bugs.jquery.com/ticket/2747 jQuery为IE7'bug'实施了一种解决方法。但是在jQuery 1.7.1中重新引入了这个bug。 我为1.7.1创建了一个新的错误:http://bugs.jquery.com/ticket/11129

答案 3 :(得分:1)

我用:

var hrefArr = $(this).attr('href').split('/');
var id = hrefArr[hrefArr.length-1];

当我需要最后一个“/".

之后的所有内容

答案 4 :(得分:1)

另一种方法是仅使用数据属性,而不是href

<a data-href="#anchor-0">example</a>

var href = $(this).attr('data-href');

答案 5 :(得分:0)

我最终通过PHP创建了一个变量,然后使用javascript replace()方法将其从href中删除:

<script>var domain = 'http://<?=$_SERVER['HTTP_HOST']?>';</script>

<script>
$(function(){
/* prevent default action of all anchors with hash class */
$('#canvas').on('click', 'a.hash', function(event) {
    event.preventDefault();
            // get the href of the anchor
    var hash = '!' + $(this).attr('href');
            // remove the absolute url if it exists
    hash = hash.replace( domain, '' );
    // redirect
            window.location.hash = hash;
});
});
</script>

答案 6 :(得分:-1)

问题是IE7和IE8也改变了文本。所以一个好的解决方法是这样做

$('#linkId').attr('href','newlink').text('oldtext');