首页 > 解决方案 > 为什么 chrome 控制台 jquery 甚至在我分配值之前就为选择选项添加了值

问题描述

我有一个选择输入,我正在通过添加另一个选项jQuery,我在这里遵循的步骤是option通过文档方法创建一个元素createElement,然后添加一些innerHTML ,最后设置value.

问题出在第二步,当我刚刚创建了一个元素并添加了innerHTML唯一的(还没有添加值)时,chrome 使用value我在下一步中添加的元素来控制该元素。

铬是如何做到这一点的?为什么?

检查下面的代码片段:

注意:此处的代码片段正确地显示了它,但是当我从单个文件 运行代码时, chrome浏览器不会。Firefox显示正确的输出。.html

$(document).ready(function() {
  $('#addSteve').on('click', function() {
    var newVal = document.createElement('option');
    newVal.text = 'Steve';
    console.log(newVal); // didn't assign a value 'hello', still consoles it;
    newVal.value = 'Hello';
    console.log(newVal); // supposed to console the value here only;

    $('#wrapper').find('select').append(newVal);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <select>
    <option value="John" selected>John</option>
    <option value="Nick">Nick</option>
    <option value="Gomez">Gomez</option>
  </select>
</div>

<button type="button" id="addSteve">Add Steve</button>

标签: javascriptjquerygoogle-chrome

解决方案


跟踪在 Chrome 中输出大约需要 8 毫秒(至少在我的计算机上,您的计算机可能更快/更慢),因此在这些毫秒之后反映变量的值。看:

$(document).ready(function() {
  $('#addSteve').on('click', function() {
    var newVal = document.createElement('option');
    newVal.text = 'Steve';
    console.log(newVal); 
    setTimeout(function(){
      newVal.value = 'Hello';
      console.log(newVal); 
    }, 8); // replace with a lower number see the value traced in the earlier console log.

    $('#wrapper').find('select').append(newVal);
  });
});

推荐阅读