javascript - 如何使用 jQuery 禁用/启用按钮?

标签 javascript jquery

我正在做一个类项目,而且我在这类事情上几乎是一个绝对的初学者。我有一个在 Ubuntu 上运行的服务器。在 script.js 里面我有

$(document).ready(function(){
    $.get('/var/www/html/hadoopstatus.txt', function(response) {
        var $hadoopstatus = response;
    }, "text");
    if ($hadoopstatus == 'Running'){
        document.getElementById('b2').disabled = false;
    }
    if ($hadoopstatus == 'Stopped'){
        document.getElementById('b1').disabled = false;
    }
});

在index.html 里面我有

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="script.js"></script>
// some stuff
</head>

<body>
// stuff
<form method="post">
<button type="submit" id="b1" disabled>Start Hadoop</button>
<button type="submit" id="b2" disabled>Stop Hadoop</button>
</form>
// stuff
</body>

/var/www/html/hadoopstatus.txt仅包含

Running

我遇到的问题是按钮(在本例中为“停止 Hadoop”按钮)将无法启用。我做错了什么?

最佳答案

$.get 函数是异步的,因此您必须等待它完成。

所以将代码更改为:

 $.get('/var/www/html/hadoopstatus.txt', function(response) {
   var $hadoopstatus = response;
   if ($hadoopstatus == 'Running') {
     document.getElementById('b2').disabled = false;
   }
   if ($hadoopstatus == 'Stopped') {
     document.getElementById('b1').disabled = false;
   }
 }, "text");

完全控制:

var jqxhr = $.get('/var/www/html/hadoopstatus.txt', function(response) {
  alert( "success" );

  if (response == 'Running') {
     document.getElementById('b2').disabled = false;
   }
   if (response == 'Stopped') {
     document.getElementById('b1').disabled = false;
   }


}, "text")
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

关于javascript - 如何使用 jQuery 禁用/启用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35854242/

相关文章:

javascript - jQuery - 使用 remove() 后点击功能不工作

javascript - 在 JavaScript 中用 "selected"替换单选按钮

javascript - 如何实现页面之间的动画

jQuery 函数 .split() 不起作用,AJAX 数据未提交

jQuery Ajax : return value to caller?

javascript - SimpleModal 基本模态窗口在选择时显示无效页面

JavaScript 当用户结束事件时调用函数

javascript - 扩展 Promise 以支持进度报告

javascript - 找到一个元素,然后在下一个之后插入内容

javascript - 一次调用即可绑定(bind)多个类的点击事件