简体   繁体   English

即使条件为假,jQuery函数也会触发

[英]jquery function firing even though condition is false

This is a real mystery for me and the other developers who have looked at it. 对于我和其他研究过它的开发人员来说,这是一个真正的谜。 I have a jquery function and within the function I have an if statement. 我有一个jQuery函数,并且在该函数中有一个if语句。 There is some code within the statement body that I want executed when the condition is true, but not executed when the condition is false. 条件为true时,我要在语句主体中执行某些代码,但条件为false时,则不执行。 Pretty simple. 很简单 However, the code within the body is being executed, EVEN when the condition is false. 但是,即使条件为假,主体中的代码也会被执行。 The variable in the condition is called delayExists (which is outside the function). 条件中的变量称为delayExists(在函数外部)。 I tested using a variable (called test) within the function and "forced" the condition to be true - ONLY in this scenario is the if statement working correctly. 我在函数内使用变量(称为测试)进行了测试,并“强制”条件为真-仅在这种情况下,if语句才能正常工作。 I've stepped through the code using Chrome Developer tools and can see when delayExists becomes true yet the condition appears to be ignored. 我已经使用Chrome Developer工具逐步检查了代码,可以看到delayExists何时变为true,但条件似乎被忽略了。 I've tried to include the pertinent code below. 我试图在下面包括相关代码。 Please let me know I need to provide more. 请让我知道我需要提供更多。

<!-- at model specifies the type of object the view expects -->
@model atdaem
<div class="tab-pane" id="tab_delays">
    <div class="row">
        <div class="col-xs-12">
            @(Html.Kendo().Grid<atdlm>().Name("delays-grid").Columns(columns =>
              {
                  columns.Bound(c => c.Id).HeaderTemplate(" ").Width(1).ClientTemplate("<span style=\"white-space:nowrap;\">" + "<button type=\"button\" class=\"btn btn-social-icon btn-linkedin\" " + "data-toggle=\"modal\" data-target=\"\\#delayAddModal\" data-guid=\"#=Id#\" data-name=\"#=LocationName#\" " +

                                                                                       "data-title=\"Edit Delay\" >" + "<i class=\"fa fa-edit\"></i></button>" + "</span>");
                  ;
              }).DataSource(dataSource => dataSource
                                              .Ajax()
                                              .Read(read => read.Type(HttpVerbs.Post)
                                                                .Action("ActualDelayList", "TrainActivity")
                                                                .Data("actualJobTaskId")))
              .Events(events => events.DataBound("delaysDatabound")))
            <div class="pull-right top-buffer">
                <button type="button" class="btn bg-green" data-toggle="modal"
                        data-title="Add Delay"
                        data-target="#delayAddModal">
                    <i class="fa fa-plus-square"></i>
                    Add delay
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="delayAddModal" tabindex="-1" role="dialog" aria-labelledby="delayAddLabel">
    <div class="modal-dialog" role="document">
        <!-- Modal content -->
        <div class="modal-content">
            <div class="modal-header">
                <!-- This "x" button is for dismissing the modal -->
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="delayAddLabel">Add Delay</h4>
            </div>
            <div class="modal-body">
<form name="delay-form" id="delay-form">
    @Html.HiddenFor(m => m.atdId, new { id = "atdId" })

    @Html.HiddenFor(m => m.ajtId)

    @*Original:*@
    <div class="form-group">
        <!-- Renders floating text ("Subdivision") above the select options -->
        @Html.LabelFor(m => m.SubdivisionId, new { @class = "field-label always-visible" })

        <!-- ID for select element -->
        <!-- Renders select class="select" id="SubdivisionId" name="SubdivisionId"><option value="4429faa8-5ad4-4adf-adde-ec7cf88ed9e9" innerHTML "Caltrain"-->
        @Html.DropDownListFor(m => m.SubdivisionId, Model.AvailableSubdivisions, new { @class = "select" })
        @Html.ValidationMessageFor(m => m.SubdivisionId)
    </div>

    <div class="row">
        <!--Start milepost -->
        <div class="col-xs-6">
            <div class="form-group">
                @Html.LabelFor(m => m.StartMilepost, new { @class = "field-label" })
                @Html.TextBoxFor(m => m.StartMilepost, new { @class = "form-control", placeholder = Html.DisplayNameFor(m => m.StartMilepost) })
                @Html.ValidationMessageFor(m => m.StartMilepost)
            </div>
        </div>
        <!-- End milepost -->
        <div class="col-xs-6">
            <div class="form-group">
                @Html.LabelFor(m => m.EndMilepost, new { @class = "field-label" })
                @Html.TextBoxFor(m => m.EndMilepost, new { @class = "form-control", placeholder = Html.DisplayNameFor(m => m.EndMilepost) })
                @Html.ValidationMessageFor(m => m.EndMilepost)
            </div>
        </div>
    </div>
    <!-- Location -->
    <div class="form-group">
        @Html.LabelFor(m => m.LocationId, new { @class = "field-label always-visible" })
        <select id="LocationId" name="LocationId" class="select">
            @foreach (var loc in Model.AvailableLocations)
            {
                <option value="@loc.Id" data-milepost="@loc.Milepost">@loc.Name</option>
            }
        </select>

        @Html.ValidationMessageFor(m => m.LocationId)
    </div>


</form>
</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <!-- call to js function-->
                <button id="delayAddButton" type="button" class="btn btn-primary" data-title="Add Delay">Add Delay</button>
            </div>
        </div>
    </div>
</div>

<script>

var delayExists = false;

    //the jquery function is listening for the element with the id #delayAddModal (which is also used for delayEdit); when that modal is shown (by someone clicking
    // on the Add Delay button which has a data-target that points to the modal), just before the modal appears this fuction executes)
    $("#delayAddModal")
        .on("show.bs.modal",
            function(event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var modal = $(this);
                var title = button.data('title'); // get New title from data-title attribute
                var delId = button.data("guid");
                var name = button.data("name");

                var conditionalVariable = 1;

                var updateButtonValue = "Save Edit";


                modal.find('.modal-title').text(title); // set title to New title
                modal.find('#delayAddButton').text(updateButtonValue); // set button value to Edit Delay


                $.ajax({
                    type: "GET",
                    url: "/TrainActivity/GetDelayDataForEditing/" + "?delayId=" + delId,
                    dataType: 'json',
                    success: function(data) {

                        delayExists = true;
                        modal.find('');

                        var sub = data.SubdivisionId;

                        $.getJSON('/TrainActivity/LocationBySubdivisionList?id=' + sub,
                            function(locs) {

                                // the stuff that needs to happen before the parent ajax completes needs to go in here
                                $('select#SubdivisionId').val(data.SubdivisionId).trigger('change');


                                $('#StartMilepost').val(data.StartMilepost);
                                $('#EndMilepost').val(data.EndMilepost);
                                $('#LocationId').val(data.LocationId).trigger('change');
                                //$('select#LocationId').val(data.LocationId).trigger('change');
                            });

                    },
                    error: function() { alert("error in Delay Edit"); }
                });


            });

    //matches location based on input in Start Milepost
    $(document)
        .ready(function() {
            var test = true;
            //matches location based on input in Start Milepost
            var button = $(event.relatedTarget); // Button that triggered the modal
            var delId = button.data("guid");
            if (test == false) {
            //if (delayExists == false) {
                $("#StartMilepost").change(function() {
                    $("#EndMilepost").val($(this).val());
                    //nearestMilepost();

                });
            }
            @*function nearestMilepost()
            {
                //var mile = parseFloat($(this).val());
                var mile = $("#@Html.IdFor(m => m.StartMilepost)").val();
                var sub = ($("#SubdivisionId").val());

                var locationId = $('#LocationId option').filter(function () {
                    return parseFloat($(this).data('milepost')) >= mile
                }).val();

                $("#LocationId").val(locationId).change();
            }



        });
            //changing the subdivision changes the locations available in the location box
            @*$("#SubdivisionId").change(function () {
                var sub = $(this).val();

                $.getJSON('@Url.Action("LocationBySubdivisionList", "TrainActivity")?id=' + sub,
                    function (locs) {
                        var list = $('#@Html.IdFor(model => model.LocationId)');
                        list.find('option').remove();
                        $(locs).each(function (index, loc) {
                            list.append('<option value="' + loc.Id + '" data-milepost="'+ loc.Milepost+'">' + loc.Name + '</option>');
                        });
                        nearestMilepost();
                    });

            });*@
        });
</script>

The misunderstanding is here: 误解在这里:

if (delayExists == false) {
  $("#StartMilepost").change(function() {
    $("#EndMilepost").val($(this).val());
    // etc.
  });
}

That check happens once , at startup. 该检查在启动时执行一次 Is delayExists false? delayExists错误吗? Yes (at startup), so we add that handler. 是(在启动时),因此我们添加了该处理程序。 Which will always run all of the code within. 它将始终运行其中的所有代码。

If you want to check the flag everytime #StartMilepost changes, you need to do that: 如果您希望每次#StartMilepost更改时都检查该标志,则需要执行以下操作:

$("#StartMilepost").change(function() {
  if (delayExists == false) {
    $("#EndMilepost").val($(this).val());
    // etc.
  }
});

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

相关问题 即使条件为假,我的功能也会自动触发 - my function is triggering automaticly even though the condition is false 即使条件不满足字符,JavaScript函数中的字符仍会重现false - Chars in Javascripts function returing false even though charcters do not satisify if condition 函数正确返回,但即使条件最终变为假,也会在while循环中超时 - Function returns correctly, but times out in while loop even though condition eventually becomes false 即使条件为假,如果条件成立,JavaScript代码执行也会进入内部 - Javascript code execution going inside if condition even though condition is false jQuery click()仍激活锚点,即使click函数返回false - jQuery click() still activates anchor, even though click function returns false 即使条件为false,Polymer 2.0 dom-if渲染模板 - Polymer 2.0 dom-if rendering template even though if condition is false 虽然循环,但额外循环即使条件为假 - While loop, extra loop even though condition is false 函数返回假甚至条件为真为什么? - Function is returning false even the condition is true why? 即使必需的输入为空,也会在Safari上触发Onsubmit功能 - Onsubmit function is firing on Safari, even though the required input is empty 即使第一个函数调用第二个函数,函数也不按正确顺序触发 - Functions not firing in correct order even though first function calls second
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM