繁体   English   中英

禁用按钮,直到“获取”完成

[英]Disable button until the “fetch” is done

我试图在单击它时禁用import_button并在fetch完成时启用它。 我试图这样做(下面的代码),但不幸的是,它不起作用。

子问题:我可以跳过这两行代码let import_button = document.getElementById('import_button'); import_button.disabled = true; let import_button = document.getElementById('import_button'); import_button.disabled = true; 并做这样的事情? this.disabled = true;

<button id="import_button" onclick="fetchProducts(event);">Import</button>
function fetchProducts(e) {
    e.preventDefault();
    let import_button = document.getElementById('import_button');
    import_button.disabled = true;
    
    fetch('/api/v1/products', {
        method: 'GET'
      })
      .then(response => response.json())
      .then(products => 
        import_result.innerHTML = `Updated: ${products.updated}`
      )
      .then(import_button.disabled = false)
}

then仍然需要是 function

.then(() => import_button.disabled = false)

或者只是将它包含在then

.then(products => {
    import_result.innerHTML = `Updated: ${products.updated}`;
    import_button.disabled = false
  })

子问题:有点。 这是活动目标

 function fetchProducts(e){ let import_button = e.target; console.log(import_button) import_button.disabled = true; }
 <button id="import_button" onclick="fetchProducts(event);">Import</button>

所以让它let import_button = e.target

您应该考虑在finally而不是then内部更改禁用的 state ,以便您也可以处理catch错误。

您可以使用this方法存储按钮引用:

function fetchProducts(e) {
    e.preventDefault();
    let import_button = this;
    
    import_button.disabled = true;
    
    fetch('/api/v1/products', {
        method: 'GET'
      })
      .then(response => response.json())
      .then(products => 
        import_result.innerHTML = `Updated: ${products.updated}`
      )
      .catch(error => console.log(error))
      .finally(() => (import_result.disabled = false))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM