2017-05-29 48 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)
在上面给出的链接中,你会发现没有这样的全局变量 –