Javascript jquery:如何将表单元素信息传递给另一个函数?
我试图在表单元素模糊上做一些事情。我遇到的问题是将元素的信息(如ID、类等)传递给第二个函数。对于这个例子,我简化了它:Javascript jquery:如何将表单元素信息传递给另一个函数?,javascript,jquery,forms,function,Javascript,Jquery,Forms,Function,我试图在表单元素模糊上做一些事情。我遇到的问题是将元素的信息(如ID、类等)传递给第二个函数。对于这个例子,我简化了它: function otherfunction() { var inputID = $(this).attr("id"); alert(inputID); } $(".formelement").blur(function () { // Do some stuff here otherfunction(); }); 当然,警报框表示inputI
function otherfunction() {
var inputID = $(this).attr("id");
alert(inputID);
}
$(".formelement").blur(function () {
// Do some stuff here
otherfunction();
});
当然,警报框表示inputID未定义。如何将元素的信息传递给Other函数?将输入作为参数传递:
function otherfunction(el) {
var inputID = $(el).attr("id");
alert(inputID);
}
$(".formelement").blur(function () {
// Do some stuff here
otherfunction(this);
});
或者,使用函数.prototype.apply
:
function otherfunction() {
var inputID = $(this).attr("id");
alert(inputID);
}
$(".formelement").blur(function () {
// Do some stuff here
otherfunction.apply(this);
});
在以下情况下使用:
$(".formelement").blur($.proxy(otherfunction, this));
以及其他javascript或:
我想你可以这样使用:
function otherfunction(obj) {
var inputID = $(obj).attr("id");
alert(inputID); }
$(".formelement").blur(function () {
otherfunction($(this));
});
哇,真不敢相信我找不到答案!非常感谢。您可以简单地使用
this.id
来访问元素的id,而不是$(this.attr('id')
之类的。。。但是,$.proxy
实际上并不调用该函数。它只返回一个函数,该函数将保证此
值。您仍然需要调用它。此外,还需要传递函数本身,而不是字符串。
function otherfunction(obj) {
var inputID = $(obj).attr("id");
alert(inputID); }
$(".formelement").blur(function () {
otherfunction($(this));
});