Wrong extraction of .attr(“href”) in IE7 vs all ot

2020-01-24 09:47发布

Can it really be true that the attr("href") command for a link is handled very different in IE7 in comparison to all other browsers?

Let's say I have a page at http://example.com/page.html and I have this HTML:

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

and this jQuery:

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

Then in IE7 the value of the strHref variable will be "http://example.com/page.htm#someAnchor" but in other browsers it will be "#someAnchor".

I believe that the last mentioned case is the most correct one, so is it just a case of IE7 being a bad boy or is it a bug in jQuery?

7条回答
对你真心纯属浪费
2楼-- · 2020-01-24 09:50

The problem is that IE7 and IE8 change also the text. So a good workaround is to do like this

$('#linkId').attr('href','newlink').text('oldtext');
查看更多
欢心
3楼-- · 2020-01-24 09:54

I believe it's implemented like that in all IE 7+.

I use:

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

Hope it helps! Cheers.

查看更多
时光不老,我们不散
4楼-- · 2020-01-24 10:02

I ended up creating a variable via PHP, then using the javascript replace() method strip it out of the 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>
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-01-24 10:07

I found a bug related to this issue: http://bugs.jquery.com/ticket/2747 jQuery implemented a workaround for the IE7 'bug'. However in jQuery 1.7.1 this bug was reintroduced. I created a new bug for 1.7.1: http://bugs.jquery.com/ticket/11129

查看更多
Evening l夕情丶
6楼-- · 2020-01-24 10:07

I use:

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

when I need everything after the last "/".

查看更多
劳资没心,怎么记你
7楼-- · 2020-01-24 10:11

It's certainly not a bug in jQuery but instead browsers' inconsistent implementations of .getAttribute('href') - I suggest using just .get(0).href for consistency.

Seems like you can access the attribute text in IE and Mozilla using .get(0).getAttribute('href', 2) if you don't want the absolute URI. Note however this won't work in Opera and I haven't tested in Safari/Chrome/anything else.

You could also strip out the domain or split on '#' for .get(0).href and use the second part of the array assuming it even contains '#' ( check .length ).

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

查看更多
登录 后发表回答