Javascript Jquery在for循环后将html元素附加到div,奇怪的行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8969255/
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
Jquery append html element to div after for loop, strange behaviour
提问by Milos911
Here is the code:
这是代码:
$('#date').append(
'<select id="date">'+
'<option value="0">- - SELECT - -</option>');
for(var i in data){
$('#date').append(
'<option value="">'+data[i]['date_time']+'</option>');
});
$('#date').append('</select>');
</select>
is always added above for loop. If i replace it with just work select for example, it is appended at the end, where it should be. Why is this happening and how can i fix it?
</select>
总是在 for 循环上面添加。例如,如果我仅将其替换为工作选择,则它会附加在最后,它应该在的位置。为什么会发生这种情况,我该如何解决?
采纳答案by andyb
I believe that jQuery will generate the DOM like this:
我相信 jQuery 会像这样生成 DOM:
<div id="date">
<select id="date">
<option value="0">- - SELECT - -</option>
</select>
<option value="">foo</option>
<option value="">bar</option>
etc...
</div>
Since it is automatically closing the <select>
after the first .append()
. What you are doing afterwards is appending the optionsto the <div id="#date"/>
rather than the <select>
that was appended. I don't think the final closing </select>
will actually do anything either.
由于它是<select>
在第一个之后自动关闭的.append()
。你在做什么事后被追加选择的<div id="#date"/>
,而不是<select>
那个被追加。我认为最后的关闭</select>
实际上也不会做任何事情。
If you really want to use append the following JavaScript will add the options to the correct node:
如果你真的想使用 append 下面的 JavaScript 会将选项添加到正确的节点:
// dummy data object for example
var data = new Array(new Array(), new Array());
data[0].date_time = 2011;
data[1].date_time = 2012;
var options = new Array();
$.each(data, function(index, option) {
options.push('<option value="' + index + '">'+ option.date_time +'</option>');
});
$('<select id="date"/>').append(options.join('')).appendTo('#date');
Assuming the existing HTML:
假设现有的 HTML:
<div id="date"></div>
However this does incur an overhead since appending is occurring twice. The faster approach is to build up the optionsmarkup as already answered by ShankarSangoli
然而,这确实会产生开销,因为追加发生了两次。更快的方法是建立已由 ShankarSangoli 回答的选项标记
回答by ShankarSangoli
It is not the right way to create html dynamically. You should create the complete markup all at once by putting it into an array and then provide it to jQuery
. Try this
这不是动态创建 html 的正确方法。您应该通过将其放入一个数组,然后将其提供给jQuery
. 尝试这个
var html = [];
html.push('<select id="date">');
html.push('<option value="0">- - SELECT - -</option>');
for(var i in data){
html.push('<option value="">'+data[i]['date_time']+'</option>');
}
html.push('</select>');
//This selector should be some container like dateContainer
//because you have already give date as id to the above select element
$('#dateContainer').html(html.join(''));
回答by Nitin
$('#date').append($("<select/>", { name: "name"+i})
.find('select')
.append($("<option/>", { value: "abc"+i}).text('cell'))
.append($("<option/>", { value: "abc"+i}).text('home'))
.append($("<option/>", { value: "abc"+i}).text('work'));
all options should wrap inside select
所有选项都应包含在选择中
回答by maeghith
I imagine the base HTML you have looks something like this:
我想象你拥有的基本 HTML 看起来像这样:
<div id="date"></div>
then after the first $('#date').append('<select id="date">...
in your code, you will have this:
然后$('#date').append('<select id="date">...
在您的代码中的第一个之后,您将拥有:
<div id="date"><select id="date">...</div>
which is 2 elements with the same ID attribute.
这是具有相同 ID 属性的 2 个元素。
The ID attribute is like the highlanders, there must only be one of them (in each page).
ID 属性就像高地人一样,必须只有一个(在每个页面中)。
The seccond $('#date').append...
works unexpectedly, and the 3rd one, also unexpectedly, doesn't work. Because you can't predict to which #date
they are referring.
第二个$('#date').append...
出乎意料地工作,第三个出乎意料地不起作用。因为你无法预测#date
他们指的是哪个。
Also, as the other answers say, it will be better if you build it to do only 1 append, because calling the selectors so many times (especially inside the loop) it's a performance hit.
此外,正如其他答案所说,如果您将其构建为仅执行 1 次追加会更好,因为多次调用选择器(尤其是在循环内)会影响性能。
回答by Cheery
If you want to do it in your way - create, for example, string variable with html code in it and than append it.
如果您想以自己的方式进行操作 - 例如,创建带有 html 代码的字符串变量,然后附加它。
data = [1, 2, 3];
var html = '<select id="date">'+
'<option value="0">- - SELECT - -</option>';
for(var i in data){
html += '<option value="">'+data[i]+'</option>';
}
$('#date').append(html)
or look here What is the best way to add options to a select from an array with jQuery?
或查看此处 使用 jQuery 从数组中选择添加选项的最佳方法是什么?
ps: the first append tries to create a valid DOM structure inside of document, closing select tag automatically. that is why the second one will not insert options into the created select.
ps:第一个 append 尝试在文档内部创建有效的 DOM 结构,自动关闭 select 标签。这就是为什么第二个不会在创建的选择中插入选项。
another possible way, based on the link above, is
另一种可能的方式,基于上面的链接,是
var sel = $('<select id="date">');
$.each(data, function(key, value) {
sel.append($('<option>').text(key['date_time']));
});
$('#date').append(sel);