0

我正在尝试创建一个动态表单,因此单击一个按钮我调用了一个 Javascript 函数。这是功能:

function addradiobutton(type){
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);   

    var foo = document.getElementById("fooBar");
    //Append the element in page (in span).
    foo.appendChild(element);
    counter=counter+1;
 }

这段代码添加了一个单选按钮,它的标签是这样的

<input type="radio" name="radio" value="radio">

但我想让这段代码像这样。

 <input type="radio" name="radio" value="radio">WATER</input>

我不介意关闭输入标签,但我想在代码末尾获得值“水”。
仅以水为例,它的价值也是动态的。
我应该怎么办 ?

4

4 回答 4

6

尝试这个

<script type="text/javascript">
        var counter = 0;
        function addradiobutton(type, text) {
            var label = document.createElement("label");

            var element = document.createElement("input");
            //Assign different attributes to the element.
            element.setAttribute("type", type);
            element.setAttribute("value", type);
            element.setAttribute("name", type);

            label.appendChild(element);
            label.innerHTML += text;

            var foo = document.getElementById("fooBar");
            //Append the element in page (in span).
            foo.appendChild(label);
            counter = counter + 1;
        }
        addradiobutton("radio", "Water");
</script>
于 2012-10-31T09:19:01.580 回答
2
<input type="radio" name="radio" value="radio">WATER</input>

… 是无效的 HTML。表达你想要表达的内容的方式是:

<label><input type="radio" name="radio" value="radio">WATER</label>

您只需要创建一个标签元素,然后创建appendChild输入元素和文本节点。

var label, input;
label = document.createElement('label');
input = document.createElement('input');
// Set type, name, value, etc on input
label.appendChild(input);
label.appendChild('Water');
foo.appendChild(label);
于 2012-10-31T09:14:53.953 回答
0

我将使用的一种解决方案是创建它而不是那样创建它:(使用jQuery以简化语法)

<div id="buttons">

</div>

<scrpit>
    var temp;
    temp = '<label><input type="radio" name="radio" value="radio" />WATER</label>';
    temp + '<label><input type="radio" name="radio" value="radio" />WATER1</label>';
    $('#buttons').html(temp);
</script>

未经测试,但逻辑应该有效,我会尝试更新错误。

如果你想要 x 数量,你可以把它放在一个带有 for 循环的函数中,循环到 x 并迭代它们。例子:

<script>
    function addButtons(number){
        for(var i=0;i<number;i++){
            // do the string appending here
        }
    }
</script>
于 2012-10-31T09:14:20.513 回答
-1

这应该有效。

element.setAttribute("innerHTML","WATER");
于 2012-10-31T09:19:18.627 回答