DOM脚本:创建元素并将它们放置在一行中

DOM scripting: create elements and position them on one line

本文关键字:一行 创建 脚本 元素 DOM      更新时间:2023-09-26

我的页面的一些背景信息:

我有一个部分总是有一个输入字段。下面有一个"添加"按钮,可以创建更多输入字段。由于屏幕上只需要一个字段后面的字段带有一个"删除"按钮,该按钮可删除相关输入字段。

以下是它的屏幕截图:http://postimg.org/image/b1yz67b1f/

如您所见,带有"-"的按钮位于每个输入框之后。我要求他们向右走。我试过了display:inline上的"-"/delete按钮无效。

代码:

function addField(count) {

    if (count<=4){
    count++;
    var id = "tag"+count;
    var newField = document.createElement("input");
    newField.setAttribute('type', 'text');
    newField.setAttribute('class', 'field');
    newField.setAttribute('id', id);
    var place = document.getElementById("tags");
    inputContainer.appendChild(newField);
    var removeId = "remove"+count;
    var remove = document.createElement("input");
    remove.setAttribute("type", "button");
    remove.setAttribute("value", "-");
    remove.setAttribute('class', 'remove');
    remove.setAttribute('id', removeId);

    remove.onclick = function () { 
        var targetInput = document.getElementById(id);
        var targetRemove = document.getElementById(removeId);
        targetInput.remove();
        targetRemove.remove();
     };
    inputContainer.appendChild(remove);
    return count;
    } 

}

您有两个选项:

  1. 将每一行包裹在自己的<div>:中

    <div><input type="text"><button>-</button></div>
    
  2. 在每行后面放一个<br>

    <input type="text"><button>-</button><br>
    

对于第一个,您必须调整JS以首先生成<div>标记,然后在其中添加输入。对于第二个,您可以在制作所有元素时附加它们,只需添加<br>元素即可。


var div = document.createElement('div');
var input = document.createElement('input');
var button = document.createElement('button');
button.innerText = '-';
div.appendChild(input);
div.appendChild(button);
inputContainer.appendChild(div);

DEMO展示了两个例子:http://jsfiddle.net/7UaAh/1/

就我理解您的问题而言,我提出了以下方法:

JS Fiddle演示

HTML:

<div id="inputContainer">
<div class="inputFieldWithButton">
<input type="text" />
<button onclick="addInput();">+</button>
</div>
</div>

JS:

var id = 1;
function addInput()
{
    var inputId = 'input'+id;
    document.getElementById("inputContainer").innerHTML += "<div id='"+inputId+"' class='inputFieldWithButton'><input type='text' /><button onclick='removeContainer("+inputId+")'>-</button></div>";
    id++;
}
function removeContainer(_inputId)
{
    document.getElementById(_inputId.id).remove();
}

希望这能有所帮助。