单击按钮,直到val = true

时间:2019-02-24 00:04:08

标签: javascript

因此,让我们考虑一个ID为phoneInput的输入,它在每次添加新内容时都会将您在文本字段中插入的内容随机排序,所以我们假设添加数字0728215523将会变得一团糟,因为它会洗牌。现在,我们有了一个按钮.shuffle,它会再次随机播放。我如何才能使按钮被点击,直到该数字是我想要的期望数字。这是我尝试过的,但没有任何反应,我的浏览器崩溃了哈哈

do {
document.querySelector('.shuffle').click()
}
while(document.querySelector('#phoneInput').value !== '0728215523')

2 个答案:

答案 0 :(得分:1)

使用事件代替do while循环。您可以在输入元素上使用keyup事件。

const phoneInput = document.getElementById('phoneInput');

const simClick = (e) => {
  if(e.target.value !== '0728215523') document.querySelector('.shuffle').click();
}

phoneInput.addEventListener('keyup', simClick)

答案 1 :(得分:1)

我认为,如果我们知道完整的实现,可能会有更有效的方法来解决此问题,但是下面的解决方案应该提供一种更为合理的方法来解决此问题...

var phoneCheck = setInterval(function (){
  if (String(document.querySelector('#phoneInput').value) === '0728215523') {
    clearInterval(phoneCheck);
  } else {
    document.querySelector('.shuffle').click();
  }
},250);
  1. 点击.shuffle
  2. 等待1/4秒(250毫秒)
  3. 检查#phoneInput值是否匹配
  4. 再次点击