未捕获的ReferenceError:未定义Bind_ChainHotel

本文关键字:未定义 Bind ChainHotel ReferenceError | 更新日期: 2023-09-27 18:26:54

我在下拉列表选择的更改上用javascript定义了一个名为Bind_ChainHotel的函数,我通过ajax将数据填充到另一个下拉列表中。我正在MVC5中使用HtmlHelper.DropDownList。每当我选择任何选项时,我都会在控制台中收到这个错误。

 @Html.DropDownList("ddlShellLevel", new List<SelectListItem>
                                                    {
                                                        new SelectListItem{Text="Chain",Value= "1"},
                                                        new SelectListItem{Text="Hotel",Value= "2"}
                                                    }, "Select Level", new { onchange = "Bind_ChainHotel(this.value);", @class = "form-control" })

Javascript

(function Bind_ChainHotel(id) {
    $.ajax({
        url: '@Url.Action("Bind_ChainHotel", "Shell")',
        type: "POST",
        data: { "id": id },
        success: function (data) {
            $("#ddlChain_Hotel").empty();
            $.each(data, function (i, chain_hotel) {
                $("#ddlChain_Hotel").append('<option value="' + chain_hotel.Value + '">' +
                     chain_hotel.Text + '</option>');
            });
            if (id == 1) {
                $('#lblChainHotel').text('Select Chain');
                $("#ddlChain_Hotel").prepend('<option value="0">Select Chain</option>');
            }
            else {
                $("#lblChainHotel").text("Select Hotel");
                $("#ddlChain_Hotel").prepend('<option value="0">Select Hotel</option>');
            }
        }
    });
})();

未捕获的ReferenceError:未定义Bind_ChainHotel

删除前括号和后括号

function Bind_ChainHotel(id) {
  $.ajax({
    .....
  });
};

Stephen Muecke的答案是对的,但他不愿意解释,所以我会解释的。

定义函数如下,注意它是定义和存储的,未执行

function Bind_ChainHotel(id) { /* do something with id */ }

现在,当您在名称中添加括号()时,可以通过函数名称调用该函数。由于函数是存储的,您可以在需要的地方和频率执行此操作:

Bind_ChainHotel("myId"); // with this invocation function is executed

在您的代码中,您同时定义和执行,函数在括号内定义,然后由末尾添加的第二个括号立即执行:

(function Bind_ChainHotel(id) { /* do something with id */ }) ();

这被称为IIFE(立即调用的函数表达式)。函数是未存储的,执行一次后,就不能再调用它了。

还有另一个不是错误,但值得注意的是:您多次编写$("#ddlChain_Hotel"),每次都会创建一个具有相同内容的新jQuery对象。这需要大量的编写和执行时间。创建一个对象并将其存储在一个变量中,然后通过其名称引用var。

// wrap the code in a $(document).ready to ensure that all DOM elements are there at runtime
$(document).ready(function() {
    var ddlChain = $("#ddlChain_Hotel"),
        lblChain = $('#lblChainHotel');
    function Bind_ChainHotel(id) {
        $.ajax({
            /* ... */
            success: function(data) {
                ddlChain.empty(); // var ddlChain holds $("#ddlChain_Hotel")
                /* ... */
            }
        });
    }
});