简体   繁体   English

材料设计复选框更改不起作用

[英]Material design checkbox change doesn't work

I am trying to dynamically set the checkbox state checked to false/true. 我正在尝试将复选框的状态动态设置为false / true。 What I have so far is this: 我到目前为止所拥有的是:

for(var i = 0; i < bookmakers.length; i++) {
    $('#' + bookmakers[i].id + '-checkbox').prop('checked', filters['bookmakers'][bookmakers[i].id]).change();
    console.log($('#' + bookmakers[i].id + '-checkbox'));
}

When I get log from the console, some of the checkboxes are checked: true and some checked: false. 当我从控制台获取日志时,某些复选框已选中:true和某些复选框:false。 The problem is that visually I see all the checkboxes checked. 问题是在视觉上我看到所有选中的复选框。 We are using material design, here is some example of the checkbox creation: 我们正在使用材料设计,这是复选框创建的一些示例:

for(var i = 0; i < bookmakers.length; i++) {
    $bookmakers.append('<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect"><input id="' + bookmakers[i].id + '-checkbox" type="checkbox" class="mdl-switch__input" checked><span class="mdl-switch__label">' + bookmakers[i].name + '</span></label>');
}

and then I do this: 然后我这样做:

if(typeof componentHandler != 'undefined')
    componentHandler.upgradeDom();

to update view. 更新视图。 Any Ideas? 有任何想法吗?

Some browsers do not allow id´s starting with a number. 某些浏览器不允许id以数字开头。 Especially CSS does not allow selectors starting with a number. 特别是CSS不允许选择器以数字开头。 Try to change #1-checkbox to #checkbox-1 尝试将#1-checkbox更改为#checkbox-1

Perhaps you should write a JSfiddle so we can see and test your code. 也许您应该编写一个JSfiddle,以便我们可以查看和测试您的代码。 In the meantime, have you tried setting the checkbox state with Javascript? 同时,您是否尝试过使用Javascript设置复选框状态?

document.getElementById('yourElemID').checked = true; // or false

There are multiple ways of solving that problem. 解决该问题有多种方法。 One I've used is this: 我使用过的一个是:

for(var i = 0; i < bookmakers.length; i++) {
    setCheckboxValue($('#' + bookmakers[i].id + '-checkbox'), filters['bookmakers'][bookmakers[i].id]);
}

and then setCheckboxValue function looks like this: 然后setCheckboxValue函数看起来像这样:

function setCheckboxValue($el, value) {
    var $parent = $el.prop('checked', value).parent();
    removeOrAddClass($parent, 'is-checked', value);
}

This is not the cleanest possible way to solve this problem. 这不是解决此问题的最干净的方法。 You can find a MaterialCheckbox object in $el.get(0) DOM Element and use it's check and uncheck methods. 您可以在$el.get(0) DOM元素中找到MaterialCheckbox对象,并使用它的checkuncheck方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM