JQuery не может получить ближайший брат - PullRequest
0 голосов
/ 07 декабря 2018

У меня есть этот HTML, который будет повторяться несколько раз.Я хочу, чтобы класс .Categories обновил ближайший класс sibling .Fields, когда запрос ajax будет выполнен.Я также пытался использовать .ind, но ни один из них не работает.

<div class="col-sm-12 row">
    <div class="col-sm-3 search-spacing">
        <label>Document Categories</label>
        @Html.DropDownListFor(m => m.CategoryId, (SelectList)Model.Categories, "Select Category", new { @class = "form-control Categories" })
    </div>
    <div class="col-sm-3 search-spacing">
        <label>Document Fields</label>
        @Html.DropDownListFor(m => m.FieldId, (SelectList)Model.DocumentFields, "Select Field", new { @class = "form-control Fields" })
    </div>
    <div class="col-sm-3 search-spacing">
        <label for="Data">Data</label>
        <input type="text" id="Data" placeholder="Search" />
    </div>
</div>

$("#datatable-search-input-container").on("change", ".Categories", function (e) {
    console.log("changed");
    selected = $(".Categories").find(":selected").val();
    var form_data = selected;
    refreshDropdown(form_data);
    return false;
});

function refreshDropdown(Input) {
    $.ajax({
            url: "@Url.Action("GetFields", @ViewContext.RouteData.Values["controller"].ToString())",
            method: "POST",
            data: JSON.stringify(Input),
            contentType: "application/json",
            success: function (result) {
                var parent = $(this).closest(".search-spacing");
                parent.find(".Fields").empty();
                console.log(parent);
            },
            error: function (error) {
                console.log(error);
            }
        });
}

Ответы [ 2 ]

0 голосов
/ 07 декабря 2018

Я бы изменил вашу функцию, чтобы передать ввод категории:

$("#datatable-search-input-container").on("change", ".Categories", function (e) {
    console.log("changed");
    var $thisCategory = $(this);
    refreshDropdown($thisCategory);
    return false;
});

function refreshDropdown(Input) {
    var form_data = Input.find(":selected").val();
    $.ajax({
            url: "@Url.Action("GetFields", @ViewContext.RouteData.Values["controller"].ToString())",
            method: "POST",
            data: JSON.stringify(form_data),
            contentType: "application/json",
            success: function (result) {
                var parent = Input.parent();
                parent.next().find(".Fields").empty();
                console.log(parent);
            },
            error: function (error) {
                console.log(error);
            }
        });
}
0 голосов
/ 07 декабря 2018

Попробуйте refreshDropdown.call(this, form_data), тогда this внутри вашего refreshDropdown относится к element, для которого было запущено event.Также кэшируйте это, потому что this изменения в вашем ajax listeners.

$("#datatable-search-input-container").on("change", ".Categories", function (e) {
        console.log("changed");
        selected = $(".Categories").find(":selected").val();
        var form_data = selected;
        refreshDropdown.call(this, form_data);
        return false;
    });

    function refreshDropdown(Input) {
        var $element = $(this),
            $nextFields = $element.parent().nextSibling().children(".Fields");

        $.ajax({
                url: "@Url.Action("GetFields", @ViewContext.RouteData.Values["controller"].ToString())",
                method: "POST",
                data: JSON.stringify(Input),
                contentType: "application/json",
                success: function (result) {
                    $nextFields.empty();
                    console.log(parent);
                },
                error: function (error) {
                    console.log(error);
                }
            });
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...