gpt4 book ai didi

javascript - 如何使用javascript在表单中的数据列表中附加元素

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

当我删除表单标签时,它可以正常工作,但是从 HTML 添加表单标签后,它就不起作用了。以下是我正在尝试的代码以及它不起作用的原因是什么

function abc() {
var i, ele, node, parent;
var num = document.getElementById("name").value;
//num=parseInt(num);
var parent = document.getElementById("listName");
var node = document.createTextNode(num);
var ele = document.createElement("option");
ele.append(node);
parent.appendChild(ele);
//alert(num);
//num++;
document.getElementById("name").value = "";
}
<form>
<input type="input" id="name" list="listName" />
<datalist id="listName"></datalist>
<input type="submit" onclick="abc()" />
</form>

最佳答案

使用 submit 值对 input 元素的属性 type 进行赋值意味着提交表单

The button documentation的确如此:

submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.

您没有任何表单,因此当前页面被视为实际表单。
当您单击按钮时,首先调用与 onclick() 关联的函数。
它在 dataList 中添加了选项,但您永远不会看到它,因为表单已提交,因此您返回到 html 页面的初始状态。

您不想提交表单,而是希望有一个按钮将点击事件绑定(bind)到一个函数。

所以不要使用 submit type 而是使用 button type 作为你的 input :

  <input type="button" value="add option" onclick="abc()" />

符合您的要求:

button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.

作为旁注,您的函数根据需要更加复杂,并且引入了太多可能产生副作用的变量。这就够了 :

function abc() {  
var nameElement = document.getElementById("name");
var newOptionElement = document.createElement("option");
newOptionElement.textContent = nameElement.value;

var listNameElement = document.getElementById("listName");
listNameElement.appendChild(newOptionElement);
nameElement.value = "";
}
<form>
<input type="input" id="name" list="listName" />
<datalist id="listName"></datalist>
<input type="button" onclick="abc()" />
</form>

关于javascript - 如何使用javascript在表单中的数据列表中附加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45879291/

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