javascript的新手,我将如何嵌入我的javascript文件并在HTML字段中运行它

New to javascript, how would I embed my javascript file and run it in an HTML field?

本文关键字:javascript HTML 字段 运行 文件 我的 新手 何嵌入      更新时间:2023-09-26

我有一个javascript中的石头,纸,剪刀模拟器(在文件中(,它接受用户输入,生成AI选择并进行比较,然后返回答案。我将如何在 HTML 字段中执行所有这些操作,以便用户可以看到正在发生的一切?代码如下:

var userChoice = prompt("Do you choose rock, paper or scissors?");
console.log("You chose: " + userChoice);
var compare = function (choice1) { 
    var choice2 = Math.random();
    if (choice2 < 0.34) {
       choice2 = "rock";
       console.log("The computer chose: " + choice2);
    } else if(choice2 <= 0.67) {
        choice2 = "paper";
        console.log("The computer chose: " + choice2);
    } else {
        choice2 = "scissors";
        console.log("The computer chose: " + choice2);
    }
    if (choice1 === choice2) {
        return "The result is a tie!";
    }
    if (choice1 === "rock") {
        if (choice2 === "scissors") {
            return "rock wins";
        } else {
            return "paper wins";
        }
    }
    if (choice1 === "scissors") {
        if (choice2 === "rock") {
            return "rock wins";
        } else {
            return "scissors win";
        }
    }
    if (choice1 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        } else {
            return "scissors win";
        }
    }
};
compare(userChoice);

这样做:将控制台.log替换为以下内容:

document.getElementById("result").innerText = "text that you want"

并添加到 HTML 中

<h2 id="result"></h2>

由于您键入jquery作为标签,因此您应该使用 jQuery 的 .html() 函数将输出插入<div>或其他元素中,而不是输出到控制台。

前任:

创造

<div id="output">
</div>

然后,不要写console.log("You chose: " + userChoice);,而是写:

$("#output").html("You chose: " + userChoice);