我有一个 js
文件,其中包含一个 $(document).ready..
block 。由于此 block 中有许多匿名函数,我决定移动它们并创建函数。问题是,当我将匿名函数更改为函数时,js 停止正常工作。
在这种情况下,我试图创建一个 destination_from_0_changed
函数来避免匿名。
例如:
之前(作品)
$(document).ready(function () {
var destination_from_0 = $("#id_form-0-destination_from");
var destination_to_0 = $('#id_form-0-destination_to');
destination_from_0.on('change', function () {
var destination_id = $(this).val();
if (destination_id==''){
return;
}
var ajax_loading_image = $('#ajax-loading-image');
destination_to_0.empty();
ajax_loading_image.show();
$.ajax({
url: '/ajax/get-destination-to-options/' + destination_id + '/',
success: function (data) {
ajax_loading_image.hide();
destination_to_0.append('<option value="" selected="selected">'+"---------" + '</option>');
$.each(data, function (key, value) {
destination_to_0.append('<option value="' + key + '">' + value + '</option>');
});
destination_to_0.change();
}
})
});
现在:(不起作用)
$(document).ready(function () {
var destination_from_0 = $("#id_form-0-destination_from");
var destination_to_0 = $('#id_form-0-destination_to');
destination_from_0.on('change', function(){
destination_from_0_changed(destination_to_0);
});
function destination_from_0_changed(destination_to_0){
var destination_id = $(this).val();
if (destination_id==''){
return;
}
var ajax_loading_image = $('#ajax-loading-image');
destination_to_0.empty();
ajax_loading_image.show();
$.ajax({
url: '/ajax/get-destination-to-options/' + destination_id + '/',
success: function (data) {
ajax_loading_image.hide();
destination_to_0.append('<option value="" selected="selected">'+"---------" + '</option>');
$.each(data, function (key, value) {
destination_to_0.append('<option value="' + key + '">' + value + '</option>');
});
destination_to_0.change();
}
})
}
你们知道问题出在哪里吗?
最佳答案
您实现的问题是当前元素上下文 this
没有引用调用事件的元素。
您可以使用 bind()
The
bind()
method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
代码
destination_from_0.on('change', function(){
destination_from_0_changed.bind(this)(destination_to_0);
});
或者,您可以使用 .call()
The
call()
method calls a function with a giventhis
value and arguments provided individually.
destination_from_0.on('change', function(){
destination_from_0_changed.call(this, destination_to_0);
});
关于javascript - JQuery 将匿名函数转换为命名函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38716323/