javascript - 让我的 javascript 输出显示在我的 HTML 中

标签 javascript html

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

要开始真正使用 javascript 并理解它,我需要有一个环境来查看我的输出是什么。我已经完成了 javascript 类(class),但需要真正了解 HTML 和 javascript。

我想做什么:

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

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

目前我不知道我的 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);

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

有人可以通过将所有内容都标记为他们所做的来帮助清理代码以使其有意义吗?

盒子?检查脚本?

谢谢:)

最佳答案

我更新了 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;

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

关于javascript - 让我的 javascript 输出显示在我的 HTML 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20530872/

相关文章:

html - 绝对定位图像和滚动条

html - Chrome 打印一些带有灰色填充的文本框

html - 垂直分布div

javascript - 为什么我不能在单独的 html 和 js 文件中使用全局变量?

javascript - 如何检查 'this' 是否具有特定属性?

javascript - 在 HTML 页面的多个位置显示变量

浏览器窗口最小化时 HTML 背景不完整

html - 固定元素在移动设备上不可见

javascript - 如何动态嵌入阻止脚本?

javascript - Node ,SSH2服务器等待输入