【问题标题】:Javascript - a link to appear if the correct word is entered into the promptJavascript - 如果在提示中输入了正确的单词,则会出现一个链接
【发布时间】:2017-09-19 11:50:13
【问题描述】:

我正在制作一个小的 javascript 演示,我希望它能够正常工作,因此当您在提示框中输入正确的单词时,它会显示一个可点击的链接(或按钮)以继续到另一个页面(目前是一个到 google 的占位符链接) 旁边还有一些文字。我想要一些关于如何有效和简单地做到这一点的建议。谢谢。

<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>

【问题讨论】:

    标签: javascript html hyperlink prompt


    【解决方案1】:

    您缺少将在txt 中连接&lt;button&gt; 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>

    【讨论】:

      【解决方案2】:

      你几乎是对的。这应该可以。

      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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 2022-07-29
        相关资源
        最近更新 更多