gpt4 book ai didi

javascript - 如何为 HTML 分离 JavaScript 脚本

转载 作者:行者123 更新时间:2023-11-30 16:48:24 24 4
gpt4 key购买 nike

我必须按照特定准则创建 HTML 页面。我不要求任何人为我做作业,但我仍然停留在第一部分。

创建并初始化三个数组。使用 for 循环来填充这些数组。将一个元素添加到一个数组的末尾。

我创建了 2 个数组并使用了一个 pop 元素。但是当我打开 .htm 时它会正确填充但是当按下创建时它会执行我的代码的第二部分。如何分离脚本?

<!DOCTYPE HTML>
<html>
<head>
<title>Testing JavaScript for Loop</title>
</head>

<body>

<p>The pop method removes the last element from an array.</p>

<button onclick="myFunction()">Create</button>
<button onclick="pop()">Pop</button>

<p id="demo"></p>

<script>


var fruits = ["Banana", " Orange", " Apple", " Mango"];

var newFruits = [];

document.getElementById("demo").innerHTML = newFruits;

function myFunction() {
for (var i in fruits) {
newFruits.push(fruits[i])
}
document.getElementById("demo").innerHTML = newFruits;
}

function pop() {
newFruits.pop();
document.getElementById("demo").innerHTML = newFruits;
}
</script>


<br>
<p>This one needs to add and element to the beginning.</p>

<button onclick="myFunction()">Create</button>
<button onclick="pop()">This button needs to add to beginning</button>

<p id="veggie"></p>

<script>


var veggies = ["Broccoli", " Carrots", " Cucumber", " Beans"];

var newVeggies = [];

document.getElementById("veggie").innerHTML = newVeggies;

function myFunction() {
for (var i in veggies) {
newVeggies.push(veggies[i])
}
document.getElementById("veggie").innerHTML = newVeggies;
}

/*need this to put an element at the beginning of the list */

function pop() {
newVeggies.pop();
document.getElementById("veggie").innerHTML = newVeggies;
}
</script>





</body>
</html>

最佳答案

在你的函数关闭之前使用return;,同时将函数放在head部分。

像这样:

   <html>
<head>
<title>Testing JavaScript for Loop</title>
<script>
function myFunction() {
for (var i in fruits) {
newFruits.push(fruits[i])
}
document.getElementById("demo").innerHTML = newFruits;
return;
}

function pop() {
newFruits.pop();
document.getElementById("demo").innerHTML = newFruits;
return;
}
</script>
</head>

<body>

<p>The pop method removes the last element from an array.</p>

<button onclick="myFunction()">Create</button>
<button onclick="pop()">Pop</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", " Orange", " Apple", " Mango"];
var newFruits = [];
document.getElementById("demo").innerHTML = newFruits;
</script>
</html>

关于javascript - 如何为 HTML 分离 JavaScript 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30899998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com