Javascript 在引导中单击关闭时隐藏模式
我有一个打开和关闭连接的按钮。当按钮处于打开状态且用户单击时。为了关闭它,会弹出一个模式并要求确认。但当按钮处于关闭状态时,不应弹出任何模式。问题是,它与切换显示“开”和“关”的按钮相同,并且附加了模态元素。即使单击“关闭”按钮,也会弹出我不想要的模式。请帮帮我Javascript 在引导中单击关闭时隐藏模式,javascript,jquery,html,twitter-bootstrap,Javascript,Jquery,Html,Twitter Bootstrap,我有一个打开和关闭连接的按钮。当按钮处于打开状态且用户单击时。为了关闭它,会弹出一个模式并要求确认。但当按钮处于关闭状态时,不应弹出任何模式。问题是,它与切换显示“开”和“关”的按钮相同,并且附加了模态元素。即使单击“关闭”按钮,也会弹出我不想要的模式。请帮帮我 if(status == 'On'){ var url = "/streams/status"; $('button[id="modal-'+ streamId + '
if(status == 'On'){
var url = "/streams/status";
$('button[id="modal-'+ streamId + '"]').click(function(){
console.log("close modal function")
$('myModal-'+ streamId).modal('hide');
$.ajax({
type: "POST",
url: url,
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]').toggleClass('btn-success btn-danger');
$('button[id="profile-'+ res.streamId + '"]').text(function (){
console.log($(this).text())
return 'Off';
});
},
error: function (res){
console.log('there was an error', res);
}
});
})
}
else{
console.log("button is off currently");
$('myModal-' + streamId).modal('hide');
var url = "/streams/status";
$.ajax({
type: "POST",
url: url,
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]').toggleClass('btn-success btn-danger');
$('button[id="profile-'+ res.streamId + '"]').text(function (){
console.log($(this).text())
return 'On';
});
},
error: function (res){
console.log('there was an error', res);
}
});
}
})
我认为您应该添加一个rel属性(off或on),检测onclick事件并检查该属性:
$('#myModal-' + streamId).click(function(event){
if($('#myModal-' + streamId).attr('rel') == 'on'){
//do ajax request ON here
//on success ajax, replace return 'off' by
$('#myModal-' + streamId).attr('rel', 'off');
}
else{
//do ajax request OFF here
//on success ajax, replace return 'on' by
$('#myModal-' + streamId).attr('rel', 'on');
}
}
这应该是可行的以下是正确的方法:
script.
function toggleStatus (streamId, statusBefore){
$.ajax({
type: "POST",
url: "/streams/status",
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]')
.toggleClass('btn-success btn-danger')
.attr('data-toggle', statusBefore == true ? "": 'modal');
$('#profile-glyphicon-'+ res.streamId).toggleClass('glyphicon-ok glyphicon-remove');
},
error: function (res){
console.log('there was an error', res);
}
});
}
$('button[id^="modal-"]').click(function(){
var streamId = this.id.split('-')[1];
toggleStatus(streamId, true);
$('myModal-'+streamId).modal('hide');
})
$('button[id^="profile-"]').on("click", function(e){
var streamId = this.id.split('-')[1];
var statusBefore;
var dataToggleStatus = $('#profile-' + streamId).attr("data-toggle");
if(dataToggleStatus=='modal'){
statusBefore = true;
e.preventDefault();
} else {
statusBefore = false;
toggleStatus(streamId, statusBefore);
}
})
您不能从成功回调返回值,ajax是异步的。顺便说一句,我认为您根本不需要返回任何值,只需使用
status=!状态
并将状态设置为booleanShows作为html页面的一部分。