2017-05-29 120 views
0

代碼的目標是每當點擊按鈕時旋轉字符串。
對於如..如果輸入字符串爲計算器
後一點擊就成了WSTACKOVERFLO
後的下次點擊它成爲OWSTACKOVERFL
等等...
我只想在JavaScript中使用閉合來解決它。
在JavaScript中使用閉合來旋轉字符串

<html> 
<script> 
var executeMe = function() { 
    var word=document.getElementById("word").value; 
    function(){ 
     word=word.slice(-1)+word.slice(0,-1); 
    return word; 
    } 
}(); 

function myFunction(){ 
    document.getElementById("demo").innerHTML = executeMe(); 
} 
</script> 
<body> 
<p>Rotate the String.</p> 
<input type="string" name="word" id="word"></input> 
<button type="button" onclick="myFunction()">Rotate</button> 
<p id="demo"></p> 
</body> 
</html> 
+0

爲什麼你的函數裏面有函數? – Weedoze

回答

1

您正在函數中使用函數。

可以使用一個簡化的代碼像下面在另一個變量僅使用一個函數

const wordDom = document.getElementById("word"); 
 

 
function rotate() { 
 
    let word = wordDom.value; 
 
    word = word.slice(-1) + word.slice(0, -1); 
 
    wordDom.value = word; 
 
    return word; 
 
}
<p>Rotate the String.</p> 
 
<input type="string" name="word" id="word"> 
 
<button type="button" onclick="rotate()">Rotate</button> 
 
<p id="demo"></p>

+0

感謝您的迴應,但你們被帶到一個全局變量。
請參考本文... [鏈接](https://www.w3schools.com/js/tryit.asp?filename=tryjs_function_counter3)
在上面給出的鏈接中,您將找不到這樣的全局變量 –

0

<!DOCTYPE html> 
 
<html> 
 
<script> 
 
var rotateWord = null; 
 
function changeValue(){ 
 
rotateWord=document.getElementById("word").value; 
 
} 
 
function executeMe() { 
 
    function get(){ 
 
     rotateWord=rotateWord.slice(-1)+rotateWord.slice(0,-1); 
 
    } 
 
    get(); 
 
    return rotateWord; 
 
}; 
 

 
function myFunction(){ 
 
    document.getElementById("demo").innerHTML = executeMe(); 
 
} 
 
</script> 
 
<body> 
 
<p>Rotate the String.</p> 
 
<input type="string" name="word" id="word" onkeyup='changeValue()'></input> 
 
<button type="button" onclick="myFunction()">Rotate</button> 
 
<p id="demo"></p> 
 
</body> 
 
</html>

存儲的輸入值,然後改變。

+0

感謝您的迴應,但你們是一個全球變數。
請參考這裏... [鏈接](https://www.w3schools.com/js/tryit.asp?filename=tryjs_function_counter3)
在上面給出的鏈接中,你會發現沒有這樣的全局變量 –