【问题标题】:Calling a function using "this"使用“this”调用函数
【发布时间】:2011-12-21 15:54:51
【问题描述】:

我的 HTML 是:

<table class="tableData" id="addUserTable" >
    <tr>
        <th class = "" name="errorMsgUser" id="errorMsg" value="" colspan="2">&nbsp;</th>
    </tr>
    <tr>
        <th class= "" > Desired Username </th>
        <td><input name="desUname" type="text" id="desUname" size="30" value=""  /></td>
    </tr>
    <tr>
        <th class= "" > Password </th>
        <td><input type="password" name="password" id="password" value="" size="30" /></td>
    </tr>               
    <tr>
        <th></th>
        <td>
            <input name="submitAddUser" type="submit" id="submitAddUser" value="Add User" />
            <input type="button" value="Clear All" id="clearUpdateForm"></input>
        </td>
    </tr>
</table>

我制作了一个通用函数,用于清除表单并聚焦第一个输入框

$.clearForm = function() {
    var parentEle = $(this).closest('form');
    parentEle.find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }});
    parentEle.find('input[type=text]:first').focus();
};

我现在如何在表单上调用此函数?例如,给定上述标记,我可以这样绑定函数吗:

$(function(){$("#clearUpdateForm").click(function(){
    $.clearForm (this);
});});

【问题讨论】:

  • '减号' ...我真的不明白你的问题。
  • 您的函数名为 clearForm,但您正在调用 resetForm。错字?
  • 标题仍然毫无意义,请更改它以反映您的实际问题..

标签: jquery html forms


【解决方案1】:

不,您必须做出决定。要么你将“this”作为参数传递给函数,要么你的函数作用于“this”的上下文。

1) 将元素作为参数传递: 在这里,您使用“this”作为指向您希望函数对其进行操作的元素的指针。必须始终明确告知您的职能部门如何开展业务。

$.clearForm = function(target) {
    var parentEle = $(target).closest('form');
    ...
};
$("#clearUpdateForm").click(function(){
    $.clearForm(this);
});

2) 设置函数的上下文: 在这里,您的函数作用于对象所在的上下文。我们可以使用 .call 或 .apply 手动设置上下文。

$.clearForm = function() {
    var parentEle = $(this).closest('form');
    ...
};
$("#clearUpdateForm").click(function(){
    $.clearForm.call(this);
});

坚持第一种技术。第二个对于制作可链接的 jquery 方法很有用,但不是你想在这里做的。

有很多资源可以阅读关于函数parameters/scope/ways-to-call-a-function

【讨论】:

    【解决方案2】:

    如果你像这样扩展jQuery.fn 对象:

    jQuery.fn.clearForm = function() {
      // `this` is a DOM element now.
      var parentEle = $(this).closest('form');
      doOtherStuff();
    };
    

    然后您可以轻松地在一个 jQuery 对象上调用它,该对象是您的表单,如下所示:

    $('#clearUpdateForm').clearForm();
    

    jQuery.fn 对象定义了可用于 jQuery 包装对象的方法。您对其进行的任何扩展都可用于所有 jQuery 包装对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      相关资源
      最近更新 更多