当 "unrelated" html select 元素没有选项 selected 时,如何退出 jQuery 事件?

How can I exit from a jQuery event when an "unrelated" html select element has had no option selected?

如果特定 select 元素没有 selected 选项,我想退出复选框的更改 ([un]check) 事件。我测试了 select 元素的值是什么 select 在我的 "ready" 函数开始时用这段代码编辑:

var unitval = $('#unitsselect').val();
alert(unitval);

警报说 "null" 所以我尝试了这个:

$("#ckbx_produceusage").change(function () {
    var unitval = $('#unitsselect').val();
    if (unitval == null) {
        return;
    }
    alert('from ckbx_produceusage change event');
});

尽管如此,它并没有通过告诉我存在 IIS 问题来开始解决方案 - 它甚至没有向我显示错误页面。但是,一旦我取消了空检查:

$("#ckbx_produceusage").change(function () {
    var unitval = $('#unitsselect').val();
    //if (unitval == null) {
    //    return;
    //}
    alert('from ckbx_produceusage change event');
});

...我看到有关选中相关复选框的警告。

那么,当 select 元素还没有从中生成 selection 时,我该如何退出事件处理程序?

更新

我尝试了 Horacio Benitez 的建议:

$("#ckbx_produceusage").change(function () {
    var unitval = $('#unitsselect').val();
    if (unitval == -1) {
        event.stopPropagation();
        event.preventDefault();
    };
    alert('from ckbx_produceusage change event');
});

...但仍然看到警报。所以我又加了一个:

$("#ckbx_produceusage").change(function () {
    var unitval = $('#unitsselect').val();
    alert(unitval);
    if (unitval == -1) {
        event.stopPropagation();
        event.preventDefault();
    };
    alert('from ckbx_produceusage change event');
});

...它是 "null"(不是“-1”)

这是将选项添加到单位的代码 select:

<select class="form-control, dropdown" id="unitsselect" name="unitsselect">
    <option disabled selected value="-1">Please choose a Unit</option>
    @foreach (var field in units)
    {
        <option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
    }
</select>

值为-1的"Please choose a Unit"是页面显示时看到的。但是选中 "ckbx_produceusage" 复选框会显示 "null" 然后 "from ckbx_produceusage change event"

当未选择单元 select 中的选项时,如何 exit/return 退出复选框的更改事件?

我们检查未selected选项的方法是给第一个选项一个值=-1和通用文本'Please select an option'强制用户select选项,因此在您的评估中,您可以询问

if($('#unitsselect').val() == "-1" ){
    event.stopPropagation(); //this line prevents the element's event propagation
    event.preventDefault(); // this line prevents the default element behaviour
};

更新

根据你的更新,我为你做了一个jfiddle https://jsfiddle.net/o30x9wvx/2/ 您元素的 disabled 属性阻止了 value = -1 的概念,在我发布的 fiddle 中您可以尝试添加 disabled 属性在第一个 option 元素上查看结果。

您可以使用变量来跟踪用户是否更改了 select 元素。

// If the change event occurs on the select element the user made a selection.
// Set a variable called unitSelectChanged to true if they do.

var unitSelectChanged = false;
$("#unitsselect").change(function(){
    unitSelectChanged = true;
});

$("#ckbx_produceusage").change(function () {
    // Exit from the handler if that variable is true
    if (unitSelectChanged) {
        return;
    }
    alert('from ckbx_produceusage change event');
});