复选框在选中时触发函数,如果未选中,则触发其他函数

Checkbox fire a function if checked and a different function if not checked

本文关键字:函数 其他 复选框 如果      更新时间:2023-09-26
嗨,我

有一个复选框,当我单击它并选中一个函数运行的框时,它的工作方式正是我想要的..现在我想运行一个不同的函数,如果它被选中,但它只是每次都运行相同的函数。

<input type="checkbox" class="no-custom" onclick="CheckBox()">
function CheckBox() {
    $("#emailMain").css({"display": "none"});
    $("#emailSame").css({"display": "inline"});
    var Mainemail = Customer().email['#text']();
    Contact().email = Mainemail;
    EmailHolder(Mainemail);
}

有什么想法可以最好地解决这个问题吗?

首先,如果你在页面中包含jQuery,你应该使用它来附加你的事件,因为它可以更好地分离关注点。然后,可以使用元素的 checked 属性来确定要调用的函数:

<input type="checkbox" class="no-custom" />
$('.no-custom').change(function() {
    if (this.checked) {
        // do something...
    }
    else {
        // do something else...
    }
});

将 ID 添加到复选框:

<input type="checkbox" id="the-checkbox" class="no-custom" onclick="CheckBox()">

然后添加一个事件侦听器,以便在它发生变化时:

$(function() {
    $('#the-checkbox').change(function() {
        if($(this).is(':checked')) {
            oneFunction();
        }
        else {
            anotherFunction();
        }
    });
    function oneFunction() {
    }
    function anotherFunction() {
    }
});

您可以使用jQuery轻松检查复选框是否被选中。

<input type="checkbox" class="no-custom" onclick="CheckBox(this)">
function CheckBox(cb) {
  if ($(cb).is(":checked")) {
    alert("Checked");
    CheckedFunction();
  } else {
    alert("Unchecked");
    UncheckedFunction
  }
}