如何通过 JavaScript 创建一个新的 HTML 复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26626853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a new HTML checkbox via JavaScript?
提问by AkshayP
I have defined a button in HTML which calls a function to create an object in my JS. In addition, i would like this button to "spawn" the creation of a new checkbox (with name and value depending on the former created object) in HTML, lets say in div id XY.
我在 HTML 中定义了一个按钮,它调用一个函数在我的 JS 中创建一个对象。此外,我希望这个按钮在 HTML 中“生成”一个新复选框的创建(名称和值取决于以前创建的对象),比如在 div id XY 中。
Though i suppose it's not important, here is my current stuff.
虽然我认为这并不重要,但这是我目前的东西。
html
html
<input id="button" value="pick Brakiri" onclick="initiate('Brakiri')">
js
js
function initiate(faction){
calc = new Calc(faction)
}
I would like to avoid jQuery if possible.
如果可能,我想避免使用 jQuery。
thank you.
谢谢。
回答by Rikard
You should create a functin for this. A example under where you pass in name
and id
and it returns a brand new element:
您应该为此创建一个功能。在那里你传递一个例子name
,并id
和它返回一个全新的元素:
function createNewCheckboxt(name, id){
var checkbox = document.createElement('input');
checkbox.type= 'checkbox';
checkbox.name = name;
checkbox.id = id;
return checkbox;
}
After you just need to choose where to add it into the DOM. Something like:
之后您只需要选择将其添加到 DOM 的位置。就像是:
form.appendChild(createNewCheckboxt('theName', 'theID'));
回答by AkshayP
You can create an <input>
element with type="checkbox"
by using the document.createElement()
method.
您可以使用方法创建一个<input>
元素。type="checkbox"
document.createElement()
This will work:
这将起作用:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a Checkbox.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("value", "abc");
x.setAttribute("name", "xyz");
document.body.appendChild(x);
}
</script>
</body>
</html>
回答by web hobbit
Hi i'm not sur if i understand your question but this the code to create a new checkbox via javascript :
嗨,我不确定我是否理解您的问题,但这是通过 javascript 创建新复选框的代码:
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
container.appendChild(checkbox);