![](/img/trans.png)
[英]Using 'onclick' in html for a javascript function only working once
[英]HTML5 and Javascript - a function appears to be working only once
伙計們,我在玩HTML5和javascript。 我當前正在做的事情如下:屏幕上有一個紫色塊,當您單擊按鈕時,它向右移動了100像素。 到目前為止,此功能仍然有效,但是該功能僅在首次運行時有效。 我找不到我的錯誤。 我正在發布整個源代碼(javascript,html和css)
<!doctype html>
<head>
<style>
#stage{
position: relative;
width : 800px;
height : 600px;
background: #c0c0c0;
border: 1px dashed black;
}
.coil{
width: 64px;
height: 64px;
background: #800080;
position: absolute;
top: 200px;
left: 50px;
}
</style>
</head>
<body>
<div id="stage">
<div class="coil"></div>
<button id="button1">move!</button>
</body>
<script>
var coil = document.querySelector(".coil");
var button = document.querySelector("#button1");
button.addEventListener("click", clickHandler2, false);
//why is it working correctly just once
function clickHandler2()
{
coil.style.left += 100 + "px";
}
</script>
當您像這樣進行添加時,它實際上並沒有添加到值中,而只是添加了一個新字符串。 在該按鈕上添加console.log,您將看到。
console.log(coil.style.left += 100 + "px");
輸出為“ 100px100px”
一種替代解決方案:
var coilPos = 100;
//why is it working correctly just once
function clickHandler2()
{
coilPos += 100;
coil.style.left = coilPos + "px";
console.log(coil.style.left += 100 + "px");
}
您必須使用閉包。 閉包上下文中的變量必須保留左值。 然后,將值應用於您使用的屬性
var actualLeft + = 100; coil.style.left = ActualLeft +“ px”;
正如nycynik所提到的,您對字符串的添加有些粗心。
嘗試這個:
function clickHandler2()
{
var before = parseInt(coil.style.left);
before = isNaN(before) ? 0 : before;
coil.style.left = before + 100 + "px";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.