2013-03-18 27 views
0

我有一個鏈接:爲什麼雙擊期望而不是單擊使用JavaScript:void(0)在Firefox中? [解決]

<a id="HeaderImage1Tab" style="display: block;" onclick="HeaderImage1Tab(this);" href="javascript:void(0)">- Header Image 1</a> 

點擊這個鏈接調用next JS代碼:

function HeaderImage1Tab(link) { 
    if (link.innerText == "+ Header Image 1") { 
     document.getElementById("HeaderImage1Table").style.display = 'block'; 
     link.innerText = "- Header Image 1"; 
    } else { 
     document.getElementById("HeaderImage1Table").style.display = 'none'; 
     link.innerText = "+ Header Image 1"; 
    } 
} 

基本上它只是顯示下方鏈接/隱藏表塊。除Firefox之外的所有瀏覽器均適用。在Firefox中,我需要雙擊鏈接才能觸發代碼並查看錶格塊。而奇怪的是,我需要雙擊第一時間,然後按預期工作。

任何建議都會很棒。謝謝!

更新#1:我正在研究asp.net網站。我也有大約15個鏈接,就像我在上面提到的那樣。

更新#2:使用textContent而不是innerText解決問題。似乎Firefox不支持inner text

更新#3:This JS剪斷的textContent修復問題在IE8及以上:

if (Object.defineProperty && Object.getOwnPropertyDescriptor && 
    Object.getOwnPropertyDescriptor(Element.prototype, "textContent") && 
    !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) 
    (function() { 
    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText"); 
    Object.defineProperty(Element.prototype, "textContent", 
     { 
     get : function() { 
      return innerText.get.call(this) 
     }, 
     set : function(x) { 
      return innerText.set.call(this, x) 
     } 
     } 
    ); 
    })(); 
+4

Firefox不支持'innerText'。你必須改用'textContent'。請參閱http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox。發生什麼事是,當你訪問innerText時,首先它們是'undefined',所以'else'分支將被執行,你設置'innerText'的地方。 – 2013-03-18 20:16:56

+1

太棒了!謝謝@FelixKling!這解決了我的問題! – 2013-03-18 20:20:45

+0

請注意,雖然'textContent'在較早的IE版本中不受支持,所以您必須首先測試哪些屬性存在。 – 2013-03-18 20:29:32

回答

3

飾演Felix克林說,在評論,innerText屬性是不是在Firefox的支持,你必須使用的textContent (here)。

雙擊正在顯示和隱藏表的原因是,第一次單擊時,它會將link.innerText(因爲該屬性不存在而未定義)比較爲「+標題圖像1」。值不相等,因此您的第二個代碼塊將運行,在鏈接對象上創建innerText屬性並將其設置爲「+標題圖像1」。之後,你的邏輯將起作用(儘管它不會成功改變鏈接中的實際文本),因爲Javascript會允許你在任何對象上設置屬性,即使這些屬性沒有做任何事情。

+0

這正是發生的事情。鏈接開始在第二個工作,但文字沒有改變。 – 2013-03-18 20:26:29

相關問題