javascript - 为什么 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>
解决方案
跟踪在 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);
});
});
推荐阅读
- kotlin - 数组列表
添加扩展 AbstractObject 的对象是不可能的。如何解决? - bluetooth - [RPi3][Bluez] 已成功连接到 BLE 设备,但无法列出 GATT 属性
- sql - 在页面的 html 中显示/嵌入代表来自 db 的每个用户的 user_id 是否安全?
- java - JavaFx 调用目标异常
- php - php无法识别其他方法中的pdo对象
- c# - ASP.Net Core 从构造函数返回结果
- ember.js - 是否可以在 Ember 中将 Torii 与 FastBoot 一起使用?
- python - “a and a or b”的目的是什么?
- html - 如何使中间TD高于侧面TD?
- rabbitmq - 关于 RabbitMQ 通道的最佳实践