我試圖在屏幕上用兩個獨立的計數器在屏幕上同步兩個圖像。以及我試圖使其模塊化,並使用一個函數,在兩個圖像上的onClick方法進行初始化。然而事情按照我的預期行事。這兩個計數器指向相同的內存位置,單擊任何圖像將從同一計數器中檢索該值。 我該如何解決它,但仍然保持模塊化?如何通過多次調用函數來初始化多個圖像的onclick
<!DOCTYPE html>
<html>
<body>
<p id="text1"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image1">
<p id="text2"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image2">
<script>
function Counter(idText,idImage){
var that = this;
that.counter = 0;
document.getElementById(idImage).onclick = function(){
document.getElementById(idText).innerHTML = (++that.counter);
};
}
var image1 = Counter("text1","image1");
var image2 = Counter("text2","image2");
</script>
</body>
</html>
櫃檯前加'new'。 – fuyushimoya