简体   繁体   English

我的javascript文件中的jQuery函数未调用

[英]jquery function in my javascript file doesn't get called

In my ASP.NET MVC application, I have a javascript file which has a jquery function in a javascript file under the Scripts folder. 在我的ASP.NET MVC应用程序中,我有一个javascript文件,该文件在Scripts文件夹下的javascript文件中具有jquery函数。 The function listens to drop down click event and fills the textbox with the selected value like below, but when I click the drop down option, this method doesn't get called and the value is not set in the text box. 该函数侦听下拉单击事件,并使用如下所示的选定值填充文本框,但是当我单击下拉选项时,不会调用此方法,并且未在文本框中设置值。 When I run with debugger (F12), if I paste the function in the debugger command line then clicking the drop down works!!!! 当我使用调试器(F12)运行时,如果将函数粘贴到调试器命令行中,则单击下拉列表有效! Not sure why the method is not registered from the javascript file. 不知道为什么未从javascript文件注册该方法。 The dropdown-menu and input text box are created using bootstrap input-group. 使用引导程序输入组创建下拉菜单和输入文本框。 The drop down is initially empty and filled by reading from a file in setup() function. 下拉菜单最初是空的,通过在setup()函数中读取文件来填充。

// In test.js
var testMap = {}

$(function () {
    $("#dropdownlistId li a").click(function () {
        var name = $(this).text();
        $("#textBoxId").val(name);
    });
});

function setup() {
    // Read name and value pair in testMap
    ...
    // Append names to drop down list
    $.each(testMap, function (key, value) {
            $("#dropdownlistId").append("<li> <a tabindex=\"-1\" href=\"#\"> " + key + "</a>  </li>");
    });
}

$(document).ready(function () {
    setup();
});

In my cshtml file, I am calling the javascript file like: 在我的cshtml文件中,我正在像这样调用javascript文件:

@section Scripts {
    @Scripts.Render("~/scripts/test.js") 
}

<div class="col-md-3">
    <div class="input-group">
        <input id="textBoxId" type="text" class="form-control" placeholder="Enter name" />
        <div class="input-group-btn">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                <span class="caret"></span>
            </button>
            <ul id="dropdownlistId" class="dropdown-menu pull-right"></ul>
        </div>
    </div>
</div>

You are running into an issue where you're trying to bind to elements that do not yet exist. 您正在遇到一个问题,您试图绑定到尚不存在的元素。 The ul#dropdownlistId exists statically in the page template, but the li 's and their children are populated after the DOM Ready (via your setup function). ul#dropdownlistId静态存在于页面模板中,但是li和它们的子级在DOM准备就绪后(通过您的设置函数)被填充。 You can change the binding to be bound to the element that always exists ( ul#dropdownlistId ) and only act on certain child elements ( li a ): 您可以更改绑定以绑定到始终存在的元素( ul#dropdownlistId ),并且仅对某些子元素起作用( li a ):

$(function () {
    $('#dropdownlistId').on('click', 'li a', function () {
        $('#textBoxId').val($(this).text());
    });
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM