console.log和return为html做了什么?

问题描述 投票:-3回答:4

当使用onclick事件时,在我的javascript代码中使用“return”和“console.log”什么都不做,而使用document.write就是这样,所以我知道它不是代码。这可能是一个愚蠢的问题,但为什么呢?当我使用Codecademy练习时,他们总是使用console.log或返回并弹出答案。

myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

    function swimWorkout() {
        return rand;
    }
</head>
<body>
    <button onclick="swimWorkout();">Find the length </button>
</body>
return console.log
4个回答
0
投票

这确实是在文档陈述和正如您所期望的那样返回值:

function swimWorkout() {
    return rand;
}

但是,这并没有达到您的期望:

<button onclick="swimWorkout();">Find the length </button>

单击该按钮时,将执行该函数并返回该值。但是没有关于如何处理该值的指令。没有理由在任何地方显示它,因为没有代码可以显示它。

你找到了一种可能显示某种东西的方法:

document.write(rand);

但是,这可能是一个有问题的方法。 document.write()无法控制文档中您想要编写内容的位置。如果在页面加载时有一些内联JavaScript执行,它应该输出正确的位置。但是在那之后的任何事情都可能不会写在你想要的地方。

相反,您可以使用其他JavaScript代码来选择元素并将其输出。例如,考虑这样的事情:

myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

function swimWorkout() {
    document.getElementById('output').innerText = rand;
}
<button onclick="swimWorkout();">Find the value</button>
<p>The value is: <span id="output"></span></p>

您可以通过绑定到click事件来进一步从HTML(也推荐)中分离JavaScript,而不是在HTML中内联函数调用:

myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

function swimWorkout() {
    document.getElementById('output').innerText = rand;
}

document.getElementById('find-value').addEventListener('click', swimWorkout);
<button id="find-value">Find the value</button>
<p>The value is: <span id="output"></span></p>

保持标记和逻辑快速分离变得更容易维护整体。


2
投票

console是浏览器中的浏览器应用程序,仅写入浏览器的开发人员工具。 console在该网站上也是如此。它只写入该网站的网页。它不会也不能改变HTML文档或DOM。

document.write是在浏览器本身内运行的javascript,它通过DOM写入HTML文档。


1
投票

“return”语句实际上是指返回您将从函数的结束进程传递的值,“console.log”将在浏览器的开发工具中记录您在控制台部分设置的数据(在浏览器上按F12并转到控制台选项卡)等

function foo() {
   // do something
   return “ran foo function”;
}

console.log(foo());

1
投票

console.log()将消息发送到控制台,而document.write()将内容添加到html文档。我没有使用Codeacademy,但我猜测在控制台(console.log语句的位置)中“弹出”的东西。每个浏览器都有一个控制台例如,在Chrome中,导航到View - > Developer - > Javascript Console以查看console.log()语句的输出。

© www.soinside.com 2019 - 2024. All rights reserved.