我有一个用 javascript 和 jQuery 编写的小型 Chrome 扩展,它应该从网页中获取一些数据。 目标 HTML 如下所示:
<div id="options">
<div class="option"><div class="checkbox">1</div></div>
<div class="option"><div class="checkbox">3</div></div>
<div class="option"><div class="checkbox">5</div></div>
<div class="option"><div class="checkbox">Other value</div></div>
...
</div>
<div id="result">0</div>
当选中任何 .checkbox
时,#result
将发生变化。我的任务是逐一检查 .checkbox
并获取每个 #result
。
var result = {};
// for each checkbox
$('#options .option').each(function(){
// check it
this.click()
// wait a bit. Of course ideally if we can wait while #result is not changed but in practice sometimes checkbox doesn't change the result. So it will be enough to wait a few seconds
// store data
result[this.text()] = $('#result').text();
// uncheck the checkbox
this.click()
// wait
});
console.log(result);
有什么想法如何正确等待吗? 谢谢
UPD:一个显示我的问题的小例子 https://codepen.io/mihajlo-osadchij/pen/MNyazz
最佳答案
正如其他人所说,您应该使用事件处理程序而不是进行手动等待。以下是如何绑定(bind)更改事件以获取已更改的复选框的值的基本示例。
如果您确实使用了诸如 setTimeout
之类的东西,那么您实际上会因为糟糕的设计而故意减慢应用程序的速度。
$('.checkbox').on('change', (evt) => {
console.log(evt.target.value);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" value="1" />
<input type="checkbox" class="checkbox" value="2" />
<input type="checkbox" class="checkbox" value="3" />
<input type="checkbox" class="checkbox" value="4" />
关于javascript - 如何在 JavaScript 中获取 `wait`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57173296/