【问题标题】:Bootstrap toggle button fires multiple change eventsBootstrap 切换按钮触发多个更改事件
【发布时间】:2021-06-04 21:47:43
【问题描述】:

我在让 Bootstrap 切换按钮工作时遇到问题 (http://www.bootstraptoggle.com/)。添加我的切换按钮如下

<input type="checkbox" checked data-toggle="toggle" data-on="Redigér" data-off="Deaktivér" data-onstyle="danger" data-offstyle="primary" id="aktiv_toggle">

该按钮用于禁用/启用字段集中的所有元素。

单击切换按钮时,我按如下方式处理更改事件:

$(function() {
     $('#aktiv_toggle').change(function() {
         alert("test");
         if ($(this).prop('checked')) {
             $("#aktiver").prop("disabled", true);
         } else {
             $("#aktiver").prop("disabled", false);
         }
     })
 })

在其中设置警报以验证我是否收到了多个更改事件(有时并非总是如此)。不知道我做错了什么?

奖励信息:触发更改事件的次数是随机的。有时只有一次,有时2或3次。

更新(问题已“改变”): 切换按钮位于一个 php 文件中,该文件使用 AJAX 加载到我的内容 DIV 中。如果我从我的 php 文件中删除我的 Togglebutton STYLE 和 SCRIPT 导入并将其与其他样式和脚本一起放入索引的 HEAD 中,则 togglebutton 可以正常工作。但这真的有必要吗,将所有 CSS 和脚本的导入放在 index.html 的 HEAD 中。是否也可以根据我加载到我的 DIV 中的页面动态加载这些包含?

【问题讨论】:

  • 这里看起来不错jsfiddle.net/dhirajbodicherla/m3dfuwz0/1 问题一定出在其他地方
  • @DhirajBodicherla:你是对的。我正在使用 AJAX 将我的页面加载到我的页面内容 div 中。我只是在需要切换按钮的 php 中添加了我的 css 和 js。显然这会导致不适当的行为,因为将样式(css)和脚本(js)移动到我的索引的标题使一切正常,不再有双三触发器。你能解释一下为什么我不能在使用 AJAX 加载的页面中引用样式和脚本文件吗? ..
  • 请将该 ajax 部分也添加到问题中以快速解决问题
  • 在 AJAX 内容页面中添加 bootstraptoggle 脚本和 css
  • 或在 div 中加载 ajax 内容后添加脚本 => $('#aktiv_toggle').bootstrapToggle();

标签: jquery twitter-bootstrap-3 togglebutton


【解决方案1】:

我使用了以下,如果我找到更好的解决方案,我也会在这里添加:

if($("#zoomCheckBox").is('*')){
    window.zoomToggleoldVal = $('#zoomCheckBox').prop('checked');
    $('#zoomCheckBox').change(function () {
        if (window.zoomToggleoldVal == $('#zoomCheckBox').prop('checked')){
            return;
        } else {
            window.zoomToggleoldVal = $('#zoomCheckBox').prop('checked');
        }
        //execute your code just oance
        console.log('test',window.zoomToggleoldVal);
    });
}

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多