2017-09-19 13 views
0

JavaScriptのデモを少し作っています。プロンプトボックスに正しい単語を入力すると、クリック可能なリンクが表示されますまたはボタン)を押して、別のページ(現在はGoogleへのプレースホルダリンク)をテキストの横に沿って進めます。私はこれを効果的かつ簡単に行う方法についていくつか提案したいと思います。ありがとう。Javascript - 正しい単語がプロンプトに入力された場合に表示されるリンク

<button onclick="myFunction()">Click me to talk to the guard</button> 
<p id="demo"></p> 
<script> 
function myFunction() { 
var txt; 
var colour = prompt("If you wanna get in to the castle tell me what the current king's favourite colour is"); 

if (colour == "red" || colour == "Red") { 
txt= "well done" + <button onclick="a href="www.google.com">Click to continuue</button> <!--incorrect code to be changed--> 
} 
else { 
txt="sorry you aren't allowed in"; 
} 
    document.getElementById("demo").innerHTML = txt; 
} 
    var txt; 
</script> 

答えて

0

あなたはtxt<button>のhtmlを連結します単一引用符が欠落しています。

'<button onclick="a href="www.google.com">Click to continuue</button>' 

、単一引用符を含めるようにコードを変更して最終的なコード

function myFunction() { 
 
var txt; 
 
var colour = prompt("If you wanna get in to the castle tell me what the current king's favourite colour is"); 
 
if (colour == "red" || colour == "Red") { 
 
txt= "well done" + '<button onclick="a href="www.google.com">Click to continuue</button>'; 
 
} 
 
else { 
 
txt="sorry you aren't allowed in"; 
 
} 
 
    document.getElementById("demo").innerHTML = txt; 
 
}
<button onclick="myFunction()">Click me to talk to the guard</button> 
 
<p id="demo"></p>

0

あなたは、ほぼ正しいです。これはうまくいくはずです。

var button = document.querySelector('button') 
 
var result = document.querySelector('#result') 
 
button.addEventListener('click', onButtonClick) 
 

 
function onButtonClick(e) { 
 
    var toInsert; 
 
    var color = prompt("If you wanna get in to the castle tell me what the current king's favourite colour is"); 
 

 
    if (color.toLowerCase() === "red") { 
 
    toInsert = 'Well done!\n\n <a href="www.google.com">Click to continue</a>' 
 
    } else { 
 
    toInsert = "sorry you aren't allowed in"; 
 
    } 
 
    result.innerHTML = toInsert; 
 
}
<button>Click me to talk to the guard</button> 
 
<div id="result"></div>

関連する問題