我有以下数组:
const users = ['freecodecamp', 'esl_sc2', 'jhovgaard'];
我正在动态创建一个 <div>
与 document.createElement();
对于每个数组项并使用 appendChild();
附加到 DOM 。例如,
HTML
<div id='twitchBox'>
<!-- <div>s for array items will go here -->
</div>
JavaScript
function initialize() {
const users = ['freecodecamp', 'esl_sc2', 'jhovgaard'];
let channelUrl = '';
for (let i = 0; i < users.length; i += 1) {
channelUrl = `https://wind-bow.gomix.me/twitch-api/channels/${users[i]}`;
ajaxRequest(channelUrl);
}
}
// called by ajaxRequest
function showChannelLogoAndName(data) {
// extracts json data that'll be used in app
const json = JSON.parse(data);
const userName = json.name;
const logoSrc = json.logo;
// creates elements for displaying channel details
const twitchBox = document.getElementById('twitchBox');
const div = document.createElement('div');
const logo = document.createElement('img');
const spanForUserName = document.createElement('span');
const anchor = document.createElement('a');
// functions called set up channel divs with logo and link
createLogo(logo, logoSrc, displayName);
createHyperLinkedUserName(anchor, spanForUserName, displayName);
// adds channel details to streamer container
div.setAttribute('id', userName);
div.setAttribute('class', 'streamers');
div.appendChild(logo);
div.appendChild(spanForUserName);
twitchBox.appendChild(div);
}
因为数组是const users = ['freecodecamp', 'esl_sc2', 'jhovgaard'];
,我期望:
-
freecodecamp
首先出现在浏览器中 -
esl_sc2
成为第二名 - 和
jhovgaard
获得第三名
但是,在多次页面重新加载后,顺序会被打乱且随机。
您可以在 gif here 中看到该行为。
为什么会这样呢?为什么<div>
的顺序不对s 总是匹配数组项的顺序?
最佳答案
您的代码没有太大问题。调用是异步的。这就是你提到的随机性。
如果您确实想进入一行,则在成功
时调用函数
本身,或者始终
即使出现错误也可以继续
下面的示例重点介绍了您应该更新 ajaxRequest
函数的内容/方式
var index = 0;
function CallMe(id) {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/users?id=' + id,
method: 'GET',
cache: false
}).success(function(data) {
$('pre').append(JSON.stringify(data[0], null, '\t'));
index++; //increment always
if (users[index] != undefined) {
//call with the next item
CallMe(users[index]);
}
}).fail(function(jqXHR, textStatus) {
console.log(jqXHR);
});
}
const users = [1, 2, 302125, 3, 10291, 4, 5]; //your users
CallMe(users[index]); //initial call for the first element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
</pre>
关于javascript - 如何使用createElement和appendChild防止页面重新加载时div重新排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665999/