[英]How do I disable/enable buttons using 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
我遇到的問題是按鈕(在這種情況下為“ Stop 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" );
});
你有兩個問題。 首先是您在回調函數中定義了$hadoopstatus
變量。 退出回調函數后,該變量將被清除。 但是另一個更嚴重的問題是您要進行AJAX調用,這可能需要幾秒鍾才能完成。 但是,在發起該調用之后,您將立即檢查$hadoopstatus
的值。
這是異步編程的問題。 您需要記住,啟動AJAX調用將在一段時間后結束。 這就是為什么有一個回調函數。 該代碼將在AJAX調用完成加載數據后運行,無論是幾毫秒還是10秒。
我調整了代碼,以使所有業務邏輯都適合您的回調函數。 AJAX調用完成后,它將從響應中創建$hadoopstatus
變量,然后檢查該值並禁用相應的按鈕。
$(document).ready(function(){
$.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");
});
請記住, $hadoopstatus
的值在此函數之外將不可用,因為您在函數內部創建了“ var”。 函數完成后,變量也將完成。 如果在AJAX調用之前使用“ var”命令,您仍然會遇到問題,因為由於加載延遲,當您的代碼嘗試運行它時,它可能不包含該值。 換句話說,在期望您的AJAX調用是瞬時的時要小心。 可能不會。
另一個可能的解決方案是:
$(function() {
$.get('hadoopstatus.txt', function(response) {
switch (response.trim()) {
case 'Running':
document.getElementById('b2').disabled = false;
break;
case 'Stopped':
document.getElementById('b1').disabled = false;
break;
}
}, "text");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<form method="post">
<button type="submit" id="b1" disabled>Start Hadoop</button>
<button type="submit" id="b2" disabled>Stop Hadoop</button>
</form>
在.get函數中評估響應。 這是一個異步功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.