l'estrazione di sbagliato .attr ( “href”) in IE7 vs tutti gli altri browser?
-
22-09-2019 - |
Domanda
Può davvero essere vero che il comando attr("href")
per un collegamento viene gestito molto diverso in IE7 in confronto a tutti gli altri browser?
Diciamo che ho una pagina alla http://example.com/page.html ed io avere questo HTML:
<a href="#someAnchor" class="lnkTest">Link text</a>
e questo jQuery:
var strHref = $(".lnkTest").attr("href");
Poi in IE7 il valore della variabile strHref
sarà "http://example.com/page.htm#someAnchor"
ma in altri browser sarà "#someAnchor"
.
Credo che l'ultimo caso citato è la più corretta, così è solo un caso di IE7 essere un cattivo ragazzo o è un bug in jQuery?
Soluzione
E 'certamente non un bug in jQuery ma invece implementazioni inconsistenti browser di .getAttribute('href')
-. Io suggerisco di usare solo .get(0).href
coerenza
Sembra che si può accedere al testo dell'attributo in IE e Mozilla usando .get(0).getAttribute('href', 2)
se non si desidera che l'URI assoluto. Nota tuttavia questo non funzionerà in Opera e non ho ancora testato in Safari / Chrome / qualsiasi altra cosa.
Si potrebbe anche nudo fuori il dominio o per parti separate del '#' per .get(0).href
e utilizzare la seconda parte della matrice ammesso che contiene anche '#' (controllare .length
).
Altri suggerimenti
Credo che sia implementato come quello in tutta IE 7 +.
Io uso:
var href=jQuery('#foo').attr('href');
href=href.substring(href.indexOf('#'));
Speranza che aiuta! Cin cin.
Ho trovato un bug relativo a questo problema: http://bugs.jquery.com/ticket/2747 jQuery implementato una soluzione per l'IE7 'bug'. Tuttavia in jQuery 1.7.1 è stato reintrodotto questo bug. Ho creato un nuovo bug per il 1.7.1: http://bugs.jquery.com/ticket/11129
Io uso:
var hrefArr = $(this).attr('href').split('/');
var id = hrefArr[hrefArr.length-1];
quando ho bisogno di tutto dopo l'ultima "/".
altro modo è usare solo un attributo dati, invece di href
<a data-href="#anchor-0">example</a>
.
var href = $(this).attr('data-href');
I finito per creare una variabile tramite PHP, quindi utilizzando il JavaScript replace () metodo della striscia fuori dalla 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>
Il problema è che IE7 e IE8 anche cambiare il testo. Quindi, una buona soluzione è quella di fare come questo
$('#linkId').attr('href','newlink').text('oldtext');