jquery:如何将表单元素信息传递给另一个函数

jquery: How to pass form element info to another function?

本文关键字:另一个 函数 信息 元素 表单 jquery      更新时间:2023-09-26

我正在尝试在表单元素模糊上做一些事情。我遇到的问题是将元素的信息(例如 ID、类等)传递给第二个函数。对于此示例,我将其简化为:

function otherfunction() {
    var inputID = $(this).attr("id");
    alert(inputID);
}

$(".formelement").blur(function () { 
// Do some stuff here
otherfunction();
}); 

当然,警报框显示输入 ID 未定义。如何将元素的信息传递给另一个函数?

将输入作为参数传递:

function otherfunction(el) {
    var inputID = $(el).attr("id");
    alert(inputID);
}

$(".formelement").blur(function () {
    // Do some stuff here
    otherfunction(this);
}); 

或者,使用 Function.prototype.apply

function otherfunction() {
    var inputID = $(this).attr("id");
    alert(inputID);
}

$(".formelement").blur(function () {
    // Do some stuff here
    otherfunction.apply(this);
}); 

在以下情况下使用 $.proxy:

$(".formelement").blur($.proxy(otherfunction, this));

否则javascript的调用或应用:

$(".formelement").blur(function () { 
    // Do some stuff here
    otherfunction.call(this); // or otherfunction.apply(this); 
});

我认为你可以这样使用:

function otherfunction(obj) {
    var inputID = $(obj).attr("id");
    alert(inputID); }

$(".formelement").blur(function () { 
otherfunction($(this));
});