我总是习惯使用jquery或其他javascript框架,但是现在我没有框架可供使用,所以我想看看是否有人知道如果可能的话我怎么能在直接的javascript中做到这一点。
基本上我有这样的div
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" />
<div id="room_fileds">
<div class='label'>Room 1:</div>
<div class="content">
<span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X </span>
<span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small</span>
</div>
</div>
我需要的是当点击添加更多按钮时,我需要基本上添加更多宽度和长度字段,或者创建整个结构,如上面的所有div,或者只是插入新的span标记以及现有的字段的。
我知道如何使用jquery或原型框架,但不幸的是我不能使用任何框架。有谁知道如何做到这一点。我会发布代码iv为此完成,但我甚至不知道在哪里beging。
答案 0 :(得分:13)
您可以使用innerHTML
属性添加内容。将id="wrapper"
添加到div
元素周围的span
,然后就可以了
var dummy = '<span>Label: <input type="text"><small>(ft)</small></span>\r\n';
document.getElementById('wrapper').innerHTML += dummy;
当然,您不需要id
并且可以使用其他DOM方法来访问div
,但我发现使用id
更简单,更清晰。这是一个快速fiddle
另请注意,您不应该内联您的css代码,也不要直接在DOM元素中附加您的javascript调用。分离DOM,Javascript和CSS将使您的生活更轻松。
答案 1 :(得分:7)
不需要创建新房间吗?
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="label">Room ' + room +':</div><div class="content"><span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X</span><span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small></span></div>';
objTo.appendChild(divtest)
}
答案 2 :(得分:2)
只需使用innerHTML
,就像这样:
btw我将div class="content"
更改为id="content"
如果您愿意,可以添加新ID。
function add_fields() {
var d = document.getElementById("content");
d.innerHTML += "<br /><span>Width: <input type='text'style='width:48px;'value='' /><small>(ft)</small></span> X <span>Length: <input type='text' style='width:48px' value='' /><small>(ft)</small</span>";
}