所以基本上我的html上有一个按钮,上面有一个小js,onclick将按钮变成绿色,再次单击时将按钮变成灰色,感觉像是在打开和关闭。这是按钮的 JS 和 HTML 代码
<script>
$('#button1').click(function() {
//Now just reference this button and change CSS
$(this).toggleClass('buttonClassA');
});
</script>
<button type="button" class="col-md-2 notice-btns btn " id="button1">
<span class="glyphicon glyphicon-phone" aria-hidden="true"></span>
<p data-bind="if : $data.emailNotification == 1 ">On</p>
<p data-bind="if : $data.emailNotification == 0 ">Off</p>
</button>
我有两个 knockout 函数,需要在单击按钮时调用 这是
self.emailNotification = ko.observable();
self.turnOnEmailNotification = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationValue/' + auth + "/" + self.emailNotification(1) ,
contentType: 'application/json; charset=utf-8'
})
.done(function(notifications) {
self.emailNotification.removeAll();
self.emailNotification.push(notifications);
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.turnOffEmailNotification = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationValue/' + auth + "/" + self.emailNotification(0) ,
contentType: 'application/json; charset=utf-8'
})
.done(function(notifications) {
self.emailNotification.removeAll();
self.emailNotification.push(notifications);
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
我尝试检查数据绑定(bind),但后来我丢失了按钮,因此需要帮助来调用 ajax 调用
$root.turnOnEmailNotification
和
$root.turnOffEmailNotification
在同一个按钮中,这样我就可以给它一种打开和关闭的感觉。
最佳答案
Checked
不是按钮元素的有效属性。相反,您可以使用 click
通过切换来实现相同的效果。
查看:
<button type="button" data-bind="click:tgle,style:{'background-color':emailNotification()==0 ? 'red':'green'}">
<p data-bind="text:$data.emailNotification() == 1 ? 'On' : 'Off' "></p>
</button>
View 模型:
var ViewModel = function() {
var self = this;
self.emailNotification = ko.observable(0);
self.tgle = function() {
self.emailNotification(self.emailNotification() == 1 ? 0 : 1)
switch (self.emailNotification()) {
case 0:
console.log('turn off ajax fired');
//turnOFFEmailNotification
//$.ajax({
// Do ajax stuff
//});
break;
case 1:
console.log('turn on ajax fired');
//turnOnEmailNotification //default off
//$.ajax({
// Do ajax stuff
//});
break;
default:
break;
}
}
};
ko.applyBindings(new ViewModel());
的工作示例 grabs
关于javascript - 使按钮的行为像复选框, knockout js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35985052/