BootstrapToggle 复选框在单击事件时调用函数

BootstrapToggle checkbox call functions on click event

我正在尝试将一些事件附加到新的 BootstrapToogle 复选框 http://www.bootstraptoggle.com/,但我不知道哪里失败了。

所以基本上我有一个 bootstrap 切换,我想根据选中的 属性(真或假)调用一些函数:

<input type="checkbox" id="editor_draw_erase" data-toggle="toggle" data-on="Draw" data-off="Erase" data-onstyle="success" data-offstyle="danger">

$(function(){
    $("#editor_draw_erase").click(function() {
    var Toggle = document.getElementById('editor_draw_erase');
      if (Toggle.checked) {
        console.log("draw")
          //call some function
      } else {
        console.log("erase")
          //call some other functions
      }
    });

})

Fiddle: https://jsfiddle.net/c7p9n62w/12/

知道我做错了什么吗?

我遇到了同样的问题。这是因为库创建了自己的元素,而您的复选框并没有真正改变。

您可以看看您的复选框是否有 class off

您可以在选中复选框时通过检查 DOM 来检查这一点。

$(".toggle").click(function() {
  if($(this).hasClass("off")){
     console.log("draw")
  } 
  else{
     console.log("erase")
  }
});

Example

添加一个外部元素来访问它

  var consoleLine = "<p class=\"console-line\"></p>";

  console = {
    log: function(text) {
      $("#console-log").append($(consoleLine).html(text));
    }
  };
  $(function() {
    $("#ids").on('click',function() {
    alert('hai');
    var Toggle = document.getElementById('editor_draw_erase');
      if (Toggle.checked) {
        console.log("draw")
          //call some function
      } else {
        console.log("erase")
          //call some other functions
      }
    });
  })
    


 //console.log("draw")
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ids"><input type="checkbox" id="editor_draw_erase" data-toggle="toggle" data-on="Draw" data-off="Erase" data-onstyle="success" data-offstyle="danger"></div>
<p>
State:
</p>
<div id="console-log"></div>

我也遇到了麻烦。这对我有用。我正在使用 JQuery 进行切换,因为我在使 data-toggle 属性起作用时遇到了问题。

  $(function() {
    $('#toggle').bootstrapToggle({
      on: 'Edit Enabled',
      off: 'Edit Disabled'
    })

     $('#toggle').change(function() {
       if($(this).prop('checked')){
         $("#message").html("this is true");
       }
       else{
         $("#message").html("this is false");
       }
     })
  })

这使用 JQuery 设置标签以及 call/perform 切换上的其他操作。