Javascript 当从另一个函数调用时,Jquery返回空对象
我有一个正常的函数可以工作,当我控制台记录这个函数时,它返回jQuery.fn.init[small.expand,context:small.expand 我的职能如下:Javascript 当从另一个函数调用时,Jquery返回空对象,javascript,jquery,Javascript,Jquery,我有一个正常的函数可以工作,当我控制台记录这个函数时,它返回jQuery.fn.init[small.expand,context:small.expand 我的职能如下: jQuery(document).on('click', 'h3.shipping-name small.expand', function (e) { var me = jQuery(this); console.log(me); var next = me.parent().next().next
jQuery(document).on('click', 'h3.shipping-name small.expand', function (e) {
var me = jQuery(this);
console.log(me);
var next = me.parent().next().next();
if (next.is(":hidden")) {
me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
} else {
me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
next.slideToggle();
});
但是如果我想从另一个函数中得到它,像这样:
var smallExpand = jQuery('h3.shipping-name small.expand');
smallExpand.on("click", function () {
expandDetails();
});
function expandDetails(e) {
alert("oki2");
var me = jQuery(this);
console.log(me);
var next = me.parent().next().next();
console.log(next)
if (next.is(":hidden")) {
me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
} else {
me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
next.slideToggle();
}
但是它只返回如下的empy对象:jQuery.fn.init{}
我做错了什么?您的实现的问题是
此
不引用它引用的当前元素窗口
对象,因此代码不起作用
您可以使用设置此
值
smallExpand.on("click", function (event) {
expandDetails.call(this, event);
});
或者,您可以将函数引用传递给附加事件处理程序
smallExpand.on("click", expandDetails);
首先在函数外设置变量,然后可以在以后检索它
var me;
然后
现在您可以在另一个函数中使用该变量
function thisorthat() {
$(‘.class’).val(me);
}
您正在以静态方法调用expandDetails 正如@Satpal所提到的,您只需执行
smallExpand.on(“单击”,expandDetails);
this
存在于smallExpand.on(“click”,function(){});
作用域中,但一旦调用expandDetails();
它就会丢失。实现的问题是this
不引用它引用的当前元素窗口
。您可以执行smallExpand.on(“click”,expandDetails>)
或expandDetails.调用(this);
而不是this
使用e
获取元素单击使用调用expandDetails.调用(this)
function thisorthat() {
$(‘.class’).val(me);
}