リンクの有効無効を切替える処理の試行錯誤まとめ

風柳亭 -本館-

風柳亭 -別館-

ソースコードIE6 SP1Firefox 1.5
function    switchLinks()
{
/* (1)  */  var ls = document.getElementsByTagName('a') ;   
    for ( var ci=0; ci < ls.length; ci++ ) {
        if ( ls[ci].href ) {
/* (2)  */  ls[ci].hrefBK = ls[ci].href ;           
/* (3)  */  ls[ci].removeAttribute('href') ;        
        }
        else if ( ls[ci].hrefBK ) {
/* (4)  */  ls[ci].href = ls[ci].hrefBK ;           
/* (5)  */  ls[ci].hrefBK = '' ;                    
        }
    }
}   //  end of switchLinks()
(1) var ls = document.links ;×(*1)×(*1)
(2) ls[ci].setAttribute('hrefBK', ls[ci].href ) ;×(*2)
(2) ls[ci].hrefBK = ls[ci].getAttribute('href') ;
(3) ls[ci].href = '' ;×(*3)×(*3)
(4) ls[ci].setAttribute('href', ls[ci].hrefBK) ;
(4) ls[ci].href = ls[ci].getAttribute('hrefBK') ;×(*4)
(5) ls[ci].removeAttribute('hrefBK') ;△(*5)
function    switchLinks6()
{
    var ls = document.getElementsByTagName('a') ;
    for ( var ci=0; ci < ls.length; ci++ ) {
        var href, hrefBK ;
        if ( href=ls[ci].getAttribute('href') ) {
            ls[ci].setAttribute('hrefBK', href ) ;
            ls[ci].removeAttribute('href') ;
        }
        else if ( hrefBK=ls[ci].getAttribute('hrefBK') ) {
            ls[ci].setAttribute('href', hrefBK ) ;
            ls[ci].removeAttribute('hrefBK') ;
        }
    }
}   //  end of switchLinks6()
(*1) 初回(ci=0)に(3)を通ったとき、ls.lengthが2→1になり、結果ループから抜けてしまう。
(*2) ls[ci].hrefBKがundefinedのまま。
(*3) hrefにnull('')を入れても、IE6では自身のHTMLファイルがあるフォルダへのリンク、Firefoxではファイル自身へのリンクとして機能してしまう。
(*4) ls[ci].hrefBK=~で代入した値は、ls[ci].getAttribute('hrefBK')では参照できない。
(*5) 関数全体としては想定通りの動きをするが、ls[ci].hrefBKの内容が消えずに残る。