让我的javascript输出显示在HTML中

Getting my javascript output to display in my HTML

本文关键字:HTML 显示 输出 我的 javascript      更新时间:2023-09-26

我相信这是一个简单的问题。

为了真正开始玩javascript并理解它,我需要有一个环境来查看我的输出。我已经上过javascript的课,但需要真正让HTML和javascript对话。

我想做的事:

让用户在文本框中输入信息,并在html中显示结果。

天空是蓝色的吗?是(使true显示在我的HTML上)天空是蓝色的吗?否(使错误显示在我的HTML中)

目前我不知道我的javascript是否在做什么!

这是我的代码:

HTML:

<form action="" onsubmit="return checkscript()">
<input type="text" name="value">
<input type="submit" value="Submit">

Javascript:

function checkscript() {
for (i=0;i<4;i++) {
    box = document.example.elements[i];
    if (!box.value) {
        alert('You haven''t filled in ' + box.name + '!');
        box.focus()
        return false;
    }
}
return true;
}
document.write(box);

我很困惑,但需要看看我正在做的事情的结果,看看在哪里可以解决问题,我尝试在chromes检查元素功能中使用控制台,但这让我更加困惑。

有人能帮助并清理代码,通过将所有事情标记为他们所做的事情来实现意义吗?

盒子?检查脚本?

感谢:)

我更新了为您制作的jsfiddle。这是一个工作版本,可能会让你开始。

HTML

<!-- I avoided all the mess of forms, since that submits to a server, and that's more than you want right now.  Note that I added ids to each input.  Ids make it very easy to access the elements later.  -->
<input type="text" name="value" id="fillIn">
<input type="button" value="Submit" id="button">

JS

// My methodology here is totally different, since I directly get the element I care about
function checkscript() {
    // find the element in the DOM
    var box = document.getElementById("fillIn");
    // check for a value
    if (box.value) {
        // if there is one, add a new div.  That's probably not what you'll want in the long run, but it gives you something to work with (and seems to match your old idea of using document.write.  I have never yet used document.write, though others with more experience than I may like the concept better.
        // This creates a new element.  If you press F12 and look at this in your debugger, you'll see it actually appear in the HTML once it's appended
        var newElement = document.createElement("div");
        // Set the value to what you want
        newElement.innerHTML = box.value;
        document.body.appendChild(newElement);
    } else {
        alert('You haven''t filled in ' + box.name + '!');
        box.focus()
        // No returns necessary, since we're not dealing with formsubmittal.
    }
}
// This hooks up the function we just wrote to the click event of the button.
document.getElementById("button").onclick = checkscript;

这可能是你想要的,也可能不是,但它至少是一个开始的地方。

开始的几件事:

1.)确保所有元件都有末端标签

<input type="text" name="value" />

注意标记末尾的反斜杠。

2.)您使用的是表单标记,它将表单提交给服务器端组件。

建议您需要使用onclick事件。它在所有输入控件上都可用。建议你从按钮开始,这样:

<input type="text" name="value" onclick="myFunction()" />
<script type="text/javascript">
function myFunction() {
   document.write("Hello");
   console.log("Hello");
}
</script>

将内容直接写入html和控制台。希望这能让你开始。

问候,

Andy