我得到了这个错误,它来自jquery框架.

它对Change事件有效,但在try 手动执行该函数时出现错误.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined -> jquery-2.1.1.js:7300

这是密码

$(document).ready(function() {
    $("#CourseSelect").change(loadTeachers);
    loadTeachers();
});

function loadTeachers() {
    $.ajax({ 
        type: 'GET', 
        url: '/Manage/getTeachers/' + $(this).val(), 
        dataType: 'json', 
        cache: false,
        success:function(data) { 
            $('#TeacherSelect').get(0).options.length = 0;    
            $.each(data, function(i, teacher) {
                var option = $('<option />');
                option.val(teacher.employeeId);
                option.text(teacher.name);
                $('#TeacherSelect').append(option);
            });
        },         
        error: function() { 
            alert("Error while getting results"); 
        }
    });
}

推荐答案

When you call loadTeachers() on DOMReady the context of this will not be the #CourseSelect element.

您可以通过在加载DOM时触发#CourseSelect元素上的change()事件来修复此问题:

$("#CourseSelect").change(loadTeachers).change(); // or .trigger('change');

Alternatively can use $.proxy to change the context the function runs under:

$("#CourseSelect").change(loadTeachers);
$.proxy(loadTeachers, $('#CourseSelect'))();

或上述的香草JS等效物,bind():

$("#CourseSelect").change(loadTeachers);
loadTeachers.bind($('#CourseSelect'));

Jquery相关问答推荐

JQuery - 从先前 Select 的下拉列表中隐藏/显示选项

如何使用 jQuery 的 drop 事件上传从桌面拖动的文件?

jQuery:获取数据属性

无限滚动jQuery插件

在 JSON 对象上使用 jQuery 的 find()

Bootstrap 3 RC 1 中的 typeahead JavaScript 模块在哪里?

jQuery从下拉列表中删除一个选项,给定选项的文本/值

如何在 Jquery 中通过索引获取子元素?

如何在 JQuery DataTable 中默认显示所有行

jquery 从特定表单获取所有输入

Rails 5:如何将 $(document).ready() 与 turbo-links 一起使用

Underscore.js 和 jQuery 互补吗?

如何在 TypeScript 中获得 jQuery 自动完成功能?

如何使用 jQuery 或纯 JS 重置所有复选框?

如何在 Bootstrap 中创建切换按钮

在某个点停止固定位置滚动?

如何复制 pinterest.com 的绝对 div 堆叠布局

jquery追加到列表的前面/顶部

textarea 的 val() 与 text()

如何在 jquery 中获取 textarea 的值?