我想从 javascript 添加一个新的 div 到我现有的 html 页面。通常我使用指令 document.createElement("div") 执行此操作,并使用方法 div.innerHTML = ""填充此 div(例如)。这在大多数情况下工作正常,但现在我想向我的 div 添加一个选择列表,并用一些数据填充这个列表。此方法不起作用:
function initEdit(){
addPanel = document.createElement("div");
addPanel.innerHTML = "<form id='addProperty' method='get'> <table>" +
"<tr> <td> <select size='4' style='width:140px; height:200px' id='object_property_selection' onClick='unSelect(\"data_property_selection\")'> </td>" +
"<td> <select size='4' style='width:140px; height:200px' id='object_selection'>" +
"<textarea style='width:140px; height:200px; display:none' id='data_selection' /> </td> </tr>" +
"<tr> <td> <select size='4' style='width:140px; height:100px' id='data_property_selection' onClick='unSelect(\"object_property_selection\")'> </td>" +
"<td> </td> </tr>" +
"<tr> <td colspan=2> <input type='button' name='Submit' style='width:100%' onClick='submitProperty()' /> </td> </tr>" +
"</table> </form>";
$('body').jAlert(contents, 'info', offset);
list1.forEach(function(element, id){
var option = document.createElement("OPTION");
option.text = option.value = property;
form.data_property_selection.options.add(element);
})
}
有人知道怎么解决吗? (顺便说一句:我不能在开始的页面中设置这段 html 代码,因为这是一个 jAlert div 的内容)
更新:解决方案
properties1.concat(properties2).forEach(function(property, id){
if (id < object_properties.length) propertyList1 += "<option value='" + property + "'>" + property + "</option>";
else propertyList2 += "<option value='" + property + "'>" + property + "</option>";
})
objects.forEach(function(feature, id) {
objectList += "<option value='" + feature._id + "'>" + feature.name + "</option>";
})
propertyList = "<form id='addProperty' method='get'> <table>" +
"<tr> <td> <select size='4' style='width:140px; height:200px' id='object_property_selection' onClick='unSelect(\"data_property_selection\")'>" +
propertyList1 + "</select> </td>" +
"<td> <select size='4' style='width:140px; height:200px' id='object_selection'>" +
objectList + "</select> </td>" +
"<textarea style='width:140px; height:200px; display:none' id='data_selection' /> </td> </tr>" +
"<tr> <td> <select size='4' style='width:140px; height:100px' id='data_property_selection' onClick='unSelect(\"object_property_selection\")'>" +
propertyList2 + "</select> </td>" +
"<td> </td> </tr>" +
"<tr> <td colspan=2> <input type='button' name='Submit' style='width:100%' onClick='submitProperty()' /> </td> </tr>" +
"</table> </form>";
最佳答案
据我所知,用这种方法实现你想要的是不可能的。不要使用 innerHTML
,您应该走很长的路,使用 createElement 创建所有内部标签,并将它们附加为子标签。使用 jQuery 可以使这项工作很多更容易。
这里是一个如何使用 jQuery 实现的例子:link , 和 official API .
或者,如果您可以先创建内部列表,则只需创建它并将其连接为字符串作为 innerHTML
的一部分(首先创建列表,然后才编辑 innerHTML
)。
关于javascript - 通过 javascript 与新创建的 html 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10179064/