Javascript jQuery计算小时数功能不工作
我试图将Javascript jQuery计算小时数功能不工作,javascript,jquery,Javascript,Jquery,我试图将$(this)值传递给jQuery函数。功能如下,但不起作用。控制台中没有错误 该功能正在启动,因为当我在顶部放置警报时,它会工作 (function($){ $.fn.calculateHours = function() { var tbody = $(this).closest('tbody'); // get closest tbody var table = $(this).closest('table'); // get closest
$(this)
值传递给jQuery函数。功能如下,但不起作用。控制台中没有错误
该功能正在启动,因为当我在顶部放置警报时,它会工作
(function($){
$.fn.calculateHours = function() {
var tbody = $(this).closest('tbody'); // get closest tbody
var table = $(this).closest('table'); // get closest table
var params = table.find('.disguise').serialize(); // parameters
$.ajax({
type: 'post',
dataType: 'json',
url: '/calculateHours',
data: params,
success: function (response) {
// loop over object
$.each(response.rows, function(index, array) {
$.each(array, function(key, value) {
$('#row_' + index).find('.' + key).html(value);
});
});
if($.isPlainObject(response.columns)) {
$.each(response.columns, function(day, hour) {
$('.totalsRow').find('.total_' + day).html(hour);
});
}
$('.totalsRow').find('.grand_total').html(response.grand_total);
}
});
}
})(jQuery);
$(document).on('change', '.disguise', function(e) {
$.fn.calculateHours();
});
您希望jquery自动设置上下文。为此,只需将函数的引用作为处理程序传递
$(document).on('change', '.disguise', $.fn.calculateHours);
向
$.fn
添加函数是为了扩展jQuery对象。换句话说,您应该在jQuery对象上调用.calculateHours
:
$(document).on('change', '.disguise', function(e) {
$(this).calculateHours();
});
虽然我的答案会起作用,但你的答案实际上更正确。