【问题标题】:Jquery Switchery checkbox disable created new checkbox on pageJquery Switchery 复选框禁用在页面上创建的新复选框
【发布时间】:2023-03-08 23:30:01
【问题描述】:

我很难禁用 Switchery 复选框 但它在页面上为我创建了另一个 Switchery 复选框。 我首先定义了很好用的复选框:

<div class="form-group">
    <label class="col-md-2">
        Additional Options
    </label>
    <div class="col-md-3">
        <div class="">
            <label>
                <input type="checkbox" id="foo1"
                       name="foo1" class="js-switch"/>
            </label>
        </div>
    </div>
</div>

现在页面加载后,我动态地想要禁用复选框,所以我这样做了:

var foo1=  document.getElementById('foo1')
var switchery = new Switchery(foo1);
switchery.disable();

它禁用了复选框,但它在我已经定义的复选框附近创建了新的复选框 我不明白为什么

【问题讨论】:

  • 你能创建工作演示代码吗?
  • 这是复杂的GUI应用程序,我不能

标签: javascript jquery checkbox switchery


【解决方案1】:

我使用了一个模板,它在他们的 JS 代码中有这个:

$(document).ready(function () {
    if ($(".js-switch")[0]) {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        elems.forEach(function (html) {
            var switchery = new Switchery(html, {
                color: '#26B99A'
            });
        });
    }
});

这会在页面加载时运行,并且可以解释为什么您会看到 2 个切换对象。您可能有一些东西在 JS 脚本中初始化它,然后在页面本身上再次执行它。

在创建切换对象后尝试启用/禁用切换对象时遇到了类似问题,因此我设置了切换对象的全局数组并添加了函数来控制它们的状态,如下所示:

var switchery_objs = [];

function enableSwitchery(id) {
    switchery_objs[id].enable();
}

function disableSwitchery(id) {
    switchery_objs[id].disable();
}

function toggleSwitchery(id) {
    switchery_objs[id].setPosition(true);
    switchery_objs[id].handleOnchange(true);
}

function setSwitchery(id, checked) {
    if((checked && !switchery_objs[id].isChecked()) || (!checked && switchery_objs[id].isChecked())) {
        switchery_objs[id].setPosition(true);
        switchery_objs[id].handleOnchange(true);
    }
}

if (window.Switchery && $(".js-switch")[0]) {
    var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
    elems.forEach(function (html) {
        switchery_objs[html.getAttribute('id')] = new Switchery(html, {
            color: '#26B99A'
        });
    });
}

有了这个,您只需调用disableSwitchery("foo1"); 将其标记为禁用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    相关资源
    最近更新 更多