简体   繁体   English

如何使用复选框启用 Javascript 代码?

[英]How to enable Javascript code with a checkbox?

I'm trying to enable a Javascript code only when I check a checkbox.我仅在选中复选框时才尝试启用 Javascript 代码。

I want to insert a script so I can enable and disable the script by only checking or unchecking the box.我想插入一个脚本,这样我就可以通过只选中或取消选中该框来启用和禁用脚本。

If you want the code to run only when the check box is checked, just wrap that code in a function, then check if that checkbox is checked at the top of said function.如果您希望代码仅在选中复选框时运行,只需将该代码包装在一个函数中,然后检查该复选框是否在所述函数的顶部被选中。 If it's not checked, return to stop the rest of the function from running.如果未选中,则return以停止运行其余函数。

function codeToRun() {

    var myCheckbox = document.getElementById("checkbox-id");

    if (!myCheckbox.checked) {
        return;
    }

    // Whatever code you want to be run
    doWhatYouWantToDoHere();
}

If the checkbox isn't checked, the function will return without running all the way through.如果未选中该复选框,则该函数将return而不会一直运行。 If it is checked, the function will run normally.如果选中,该功能将正常运行。

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

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