[英]Changing button text and behavior using jQuery
我有一個JS方法,該方法根據按鈕的狀態而變化,該狀態由indexOf("..some text..")
$('#add1').click(function(){
if($(this).text().indexOf("Add Me!")) {
$.ajax({
type: 'post',
url: '{{ URL('schedulizer/add') }}',
data: {
"class": ["Saab", "Volvo", "BMW"],
_token: "{{ csrf_token() }}"
},
dataType: 'json'
}).done(function(data){
... do stuff ...
});
$(this).removeClass('btn-material-yellow-600');
$(this).addClass('btn-danger');
$(this).text('Remove Me!');
return false;
} else if($(this).text().indexOf("Remove Me!")){
$.ajax({
type: 'post',
url: '{{ URL('schedulizer/remove') }}',
data: {
"class": ["Saab", "Volvo", "BMW"],
_token: "{{ csrf_token() }}"
},
dataType: 'json'
}).done(function(data){
... do stuff ...
});
$(this).removeClass('btn-danger');
$(this).addClass('btn-material-yellow-600');
$(this).text('Add Me!');
return false;
}
});
什么有效:
當我單擊初始的“添加我!”時,它將更改為“刪除我!”。 但是,當按鈕的狀態為“刪除我!”時,條件不成立,無論我按了多少次按鈕,狀態都保持為“刪除我!”。
為混亂而又冗長的代碼表示歉意。我對JS還是很陌生,所以一切都是爛攤子。
indexOf返回它找到的字符串的位置,並且字符串的位置使條件if / else混亂,並且它始終落在else if條件上。 使用==
運算符,如下所示:
$('#add1').click(function(){ if($(this).text().trim() == "Add Me!") { $(this).text('Remove Me!'); return false; } else if($(this).text().trim() == "Remove Me!"){ $(this).text('Add Me!'); return false; } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="add1">Add Me!</button>
當在條件條件中使用indexOf()
需要進行比較,因為0
是有效索引,但在條件條件中則是虛假的。
使用greater than -1
進行真實性測試,因為如果不存在索引,它將為-1
if($(this).text().indexOf("Add Me!") >-1)..
HTML
<button id="add1">Add Me!</button>
使用Javascript / jQuery的
$add1Btn = $('#add1');
$add1Btn.click(function() {
var btnText = $add1Btn.html();
console.log(btnText);
if (btnText === 'Add Me!') {
$add1Btn.html('Remove Me!');
} else if (btnText === 'Remove Me!') {
$add1Btn.html('Add Me!');
}
});
如果事情似乎無法正常進行,則您的AJAX呼叫可能會引起問題。 另外,我認為您可能希望將文本更改放入AJAX調用的成功調用中,這樣,一旦收到響應,文本就會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.