【发布时间】:2022-12-18 00:43:35
【问题描述】:
表单事件练习
是时候练习使用表单和表单事件了! index.html 已经有一个包含两个元素的表单元素,一个用于数量,一个用于产品名称。 index.html 还包含一个空的
<ul>,您将在其中附加新的<li>。观看底部的 gif 动画,大致了解您的代码应如何工作。您的任务是执行以下步骤:监听表单提交
提交表单时,防止默认行为
抓取数量输入值和产品输入值
创建一个新的<li>元素。在新的<li>上设置文本以包含表单中的数量和产品名称。
将新的<li>追加到页面上的<ul>
重置输入请注意:
- Udemy 的界面还不能识别一些较新的 JS 语法,例如
.append()
您将需要为此方法使用备用(旧)语法才能使测试通过。- 表单需要分配给名为 form 的变量才能通过测试,我已经在 app.js 代码中为您包含了这行代码
索引.html
<!DOCTYPE html> <head> <title>Grocery List</title> <!--LEAVE THESE LINES ALONE, PLEASE! THEY MAKE THE LIVE PREVIEW WORK!--> <script src="node_modules/babel-polyfill/dist/polyfill.js" type="text/javascript"> </script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <h1>Grocery List</h1> <form action="/nowhere"> <label for="item">Enter A Product</label> <input type="text" id="product" name="product"> <label for="item">Enter A Quantity</label> <input type="number" id="qty" name="qty"> <button>Submit</button> </form> <ul id="list"></ul> </body> </html>应用程序.js
const form = document.querySelector('form'); const qty = document.querySelector('#qty'); const product = document.querySelector('#product'); const list = document.querySelector('#list'); form.addEventListener('submit', function (e){ e.preventDefault(); const productName = input.value; const qtyItem = input.value; const li = document.createElement('LI'); li.innerText = product; li.innerText = qty; list.appendChild(product); list.appendChild(qty); });
【问题讨论】:
-
请更新您的问题并使用 HTML、JS、CSS 创建代码 sn-ps。
-
我是 stackoverflow 网站的新手,所以如果我的帖子让你们感到困惑,我很抱歉,也许我忘了编辑一些内容,或者我不知道该怎么做,我希望你们能理解我的问题。
-
查看 productName 和 qtyItem 的代码。没有变量
input。您可能指的是 product.value 和 qty.value。从那里开始,您需要重写函数的其余部分以将文本值放入 LI,而不是 dom 元素。请注意 li.innerText = "thing1" follower by li.innerText = "thing2" 只会显示 thing2。
标签: javascript