2017-05-29 13 views
0

コードの目的は、ブーンがクリックされるたびに文字列を回転させることです。例えばのために
...入力文字列が次の私はJavaScriptでクロージャを使用して、それを解決したい、それがOWSTACKOVERFL
なりクリックのように...
した後、それはWSTACKOVERFLO
なりクリックした後にStackOverflow
ある場合。
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

関数内で関数を使用していました。

は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

応答をありがとうが、皆さんはグローバル変数になります。
これを参照してください... [link](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

ありがとうございますあなたはグローバル変数になります。
これを参照してください... [link](https://www.w3schools.com/js/tryit.asp?filename=tryjs_function_counter3)
上記のリンクでは、そのようなグローバル変数は見つかりません –

関連する問題