2015-11-01 18 views
0

我有一個表中輸入以下內容:計數器顯示永久性即使的onclick

<tr> 
    <td class="right-middle user">Name</td> 
    <td class="right-middle done"> 
     <div onload="clickCounter()" id="result"></div> 
    </td> 
    <td class="right-middle check"> 
     <img src="img/check.png" onclick="clickCounter()"> 
    </td> 
    <td class="right-middle undone"> 
     <div onload="addcounter()" id="result2"></div> 
    </td> 
    <td class="right-middle uncheck"> 
     <img src="img/uncheck.png" onclick="addCounter()"> 
    </td> 
</tr> 

及以下的javascript:

function clickCounter() { 
    if (typeof (Storage) !== "undefined") { 
     if (localStorage.clickcount) { 
      localStorage.clickcount = Number(localStorage.clickcount) + 1; 
     } else { 
      localStorage.clickcount = 1; 
     } 
     document.getElementById("result").innerHTML = localStorage.clickcount; 
    } else { 
     document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage..."; 
    } 
} 

document.getElementById("result").innerHTML = localStorage.clickcount; 


function addCounter() { 
    if (typeof (Storage) !== "undefined") { 
     if (localStorage.clickcounts) { 
      localStorage.clickcounts = Number(localStorage.clickcounts) + 1; 
     } else { 
      localStorage.clickcounts = 1; 
     } 
     document.getElementById("result2").innerHTML = localStorage.clickcounts; 
    } else { 
     document.getElementById("result2").innerHTML = "Sorry, your browser does not support web storage..."; 
    } 
} 

document.getElementById("result2").innerHTML = localStorage.clickcounts; 

我要顯示在屏幕上兩個計數器所有的時間,即使在刷新頁面之後,無需按下按鈕即可查看該值。我已經使用了這些代碼,並且它們工作正常。任何人都可以幫助我理解爲什麼計數器不會一直顯示在屏幕上?

+0

你可以做一個jsFiddle嗎? –

+0

@BasvanStein - Stackoverflow已經支持[inline live demos](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)一年多了。沒有必要依靠第三方網站來託管問題的部分內容或回答問題。 – Quentin

+0

@Quentin當然,這也很好,道歉。 –

回答

1

Div元素沒有load事件。只有從其他URL(如圖像和框架)和文檔本身獲取其內容的元素纔會這樣做。

由於您正在使用固有事件屬性([雖然它們存在問題](Why can't I call a function named clear from an onclick attribute? )),但如果您使用了a validator,則會發現該內容。

或者:

  • 只要運行在要與
  • 使用文檔的Load事件
+0

http://jsfiddle.net/g334tgby/1/幾周前,我問了一個類似的問題,我提供了這個工作小提琴,我可以在其他情況下實施。這裏onload與div –

+0

@AlexResiga - 不,它不。我[改變](http://jsfiddle.net/g334tgby/2/)刪除身體內容的功能。如果div上的加載事件起作用,身體會立即消失,但直到您單擊該按鈕纔會消失。 – Quentin

+0

哦,我明白了。我是一個初學者,所以你可以告訴我如何讓計數器始終顯示在屏幕上?小提琴真的可以幫助 –

1

onload()事件的互動元素後會出現一個腳本元素的功能不能用於任何其他元素,只能使用一組有限的標籤:<body><frame><frameset><img><link><script>