javascript - 如何使用createElement和appendChild防止页面重新加载时div重新排序?

标签 javascript

我有以下数组:

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/

相关文章:

javascript - Node.js 和未定义的属性

javascript - Cypress 无法识别我试图通过占位符查找的元素

javascript - 仅使元素符号可点击

javascript - 如何在javascript中检测鼠标右键释放事件?

javascript - tinymce 自定义按钮替换内容

javascript - 在 Typescript 中导入 CouchDB Nano 6.4 打字

javascript - 在 Firefox 中使用 indexedDB 时出现错误 "Operation failed for reasons unrelated to the database..."

javascript - 动态设置/更改事件处理程序是不好的做法吗?

javascript - 显示隐藏的第 n 个子项 onclick

javascript - 控制流不在 jquery 对话框中等待