MDL: Set Switch state to “on” via JS

2019-07-25 05:26发布

问题:

I can access my switch via let iSwitch = document.getElementById('interestedSwitch');

I looked at github and found the method MaterialSwitch.on(), but iSwitch.MaterialSwitch.on(); is undefined. iSwitch.checked = true; does not help either. I am using AngularJS, if this could be a source of the problem.

回答1:

Assuming interestedSwitch is the input element with class mdl-switch__input you need to access the parent element. This should be the label with mdl-js-switch (with MaterialSwitch component). Then you can try something like:

if(parent) {
        if(parent.MaterialSwitch && parent.MaterialSwitch.checkToggleState) {
            /* update MDL state if it was changes form javascript */
            parent.MaterialSwitch.checkToggleState();
        }
    }