简体   繁体   English

jquery $ .each是非阻塞的吗?

[英]jquery $.each is non-blocking?

$("<ol>").appendTo(some_div);
$.each(map, function(i,example){
  $("<li>" + example + "</li>").appendTo(some_div)
});
$("</ol>").appendTo(some_div);

expected: <ol><li>example1</li><li>example2</li></ol> 预期: <ol><li>example1</li><li>example2</li></ol>

actual: <ol></ol><li>example1</li><li>example2</li> 实际: <ol></ol><li>example1</li><li>example2</li>

Any idea why this happens? 知道为什么会这样吗?

You are doing DOM operations and not string operations. 您正在执行DOM操作而不是字符串操作。 And $("<ol>") does already create an OL element and not just a string containing <ol> . 并且$("<ol>")已经创建了一个OL元素,而不仅仅是一个包含<ol>的字符串。

You need to append the LI elements to the newly created OL element: 您需要将LI元素附加到新创建的OL元素:

var ol = $("<ol>").appendTo(some_div);
$.each(map, function(i,example){
    $("<li>" + example + "</li>").appendTo(ol);
});

You should append your <li> entries to your <ol> . 您应该将<li>条目附加到<ol> Otherwise you can't know how browser is going to handle your code. 否则,您无法知道浏览器将如何处理您的代码。 Additionally, you should append <ol></ol> instead of separate <ol> and </ol> . 此外,您应该附加<ol></ol>而不是单独的<ol></ol> jQuery's .append and .appendTo are not string operations, those are modifying page DOM tree. jQuery的.append.appendTo不是字符串操作,它们正在修改页面DOM树。

$("<ol></ol>").appendTo(some_div);
olelement = $(some_div).find("<ol>")
$.each(map, function(i,example){
  $("<li>" + example + "</li>").appendTo(olelement);
});

This line 这条线

$("<ol>").appendTo(some_div);

isn't simply adding an open tag as you think it is. 不是简单地添加一个你认为的开放标签。 jQuery is building an ordered list element and adding it to some_div. jQuery正在构建一个有序列表元素并将其添加到some_div。 Likewise, your $.each is appending list item elements to some_div, so they're ending up as siblings of the list. 同样,你的$ .each将列表项元素追加到some_div,因此它们最终成为列表的兄弟。 You need to append the list items to the list element. 您需要将列表项附加到列表元素。

I believe $("<ol>").appendTo creates the full <ol></ol> tag. 我相信$("<ol>").appendTo创建完整的<ol></ol>标签。 Either append the li items to the OL you've created, or create a long string and then do one append. 将li项附加到您创建的OL,或者创建一个长字符串,然后执行一个追加。 Append is an expensive operation, if you're going to have 10s or more list items you should do the latter. 追加是一项昂贵的操作,如果你有10个或更多的列表项,你应该做后者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM