简体   繁体   English

Javascript/jQuery append html 到页面加载前的 UL 元素

[英]Javascript/jQuery append html to an UL element before page loads

I have a title bar on my web page that sets a message to the user.我的 web 页面上有一个标题栏,用于向用户设置消息。 The title is created dynamically by javascript.标题由 javascript 动态创建。 I would like the content to appear without any visible delay in the page where the UL doesn't contain any LI, and then suddenly they're populated.我希望内容在 UL 不包含任何 LI 的页面中出现没有任何明显延迟,然后突然它们被填充。 Is this possible?这可能吗? What javascript DOM loading event do I want to use?我想使用什么 javascript DOM 加载事件?

The reason you typically have to wait for the document to load ( document.ready these days) is so that the element exists within the DOM so you can select it.您通常必须等待文档加载(这些天document.ready )的原因是该元素存在于 DOM 中,因此您可以 select 它。 If the element you need to modify already exists within the page, you won't need to wait.如果页面中已经存在需要修改的元素,则无需等待。

The following example won't work以下示例不起作用

<script>
  var foo = document.getElementById('foo');
  ...do more stuff with foo...
</script>
<div id="foo"></div>

It wont work because the DOM hasn't loaded div#foo when the script is executed它不会工作,因为执行脚本时 DOM 没有加载div#foo

The following example will work以下示例起作用

<div id="foo"></div>
<script>
  var foo = document.getElementById('foo');
  ...do more stuff with foo...
</script>

It works because div#foo has already been parsed and the element exists.它之所以有效,是因为div#foo已经被解析并且元素存在。

There's no particular event that you can listen for with JavaScript for cross-browser node creation.对于跨浏览器节点创建,您没有可以使用 JavaScript 监听的特定事件。 But if your script can be placed after the element has been created, you can work with the element instantaneously.但是,如果您的脚本可以在元素创建放置,您可以立即使用该元素。

Generally speaking, in Javascript when you want something to appear smoothly, even though building that something is not smooth, what you do is just hide everything until it is ready.一般来说,在 Javascript 中,当您希望某些东西看起来平滑时,即使构建该东西并不平滑,您所做的只是将所有内容隐藏起来,直到它准备好。

In other words, if you do:换句话说,如果你这样做:

<ul style="display:none"></ul>

then add some Javascript to add the LIs, then show the UL, you should have the effect you want.然后添加一些Javascript来添加LI,然后显示UL,你应该有你想要的效果。 The JS to add the LIs can go anywhere after the UL, or anywhere before if you put the logic inside an onReady or onLoad handler.添加 LI 的 JS 可以 go 在 UL 之后的任何位置,或者如果您将逻辑放入 onReady 或 onLoad 处理程序之前的任何位置。

Here's a quick jQuery example:这是一个快速 jQuery 示例:

<ul id="myList" style="display:none"></ul>
<script>
for (var i = 0; i < 5; i++) {
    $("#myList").append("<li>" + i + "</li>");
}
$("#myList").show();
</script>

ie. IE。 start the UL hidden, add stuff to it, then show it.启动隐藏的 UL,向其中添加内容,然后显示它。 Hope that helps.希望有帮助。

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

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