【问题标题】:Using $(this) for all input text types in jquery对 jquery 中的所有输入文本类型使用 $(this)
【发布时间】:2014-07-29 17:16:43
【问题描述】:
<input type="text" id="txtOMSourceName" onkeypress="hideSpan()"/>
<input type="text" id="txtMPName" onkeypress="hideSpan()"/>

如果没有输入数据,我正在验证页面上的多个文本框并将其标记为错误。我正在向这些文本框添加错误类。当他们开始在文本框中输入时,我想删除错误类。我想在 jquery 中使用它来引用当前文本框而不是 ID,这样我就可以在其他页面上重用代码。

我在文本框的按键上调用 hideSpan。它在我指定 ID 时起作用。但不是用这个关键字

function hideSpan() {
 /*  $('#txtOMSourceName').removeClass('error');
     $('#ddlOMSite').removeClass('error');
     $('#txtMPName').removeClass('error');
     $('#txtOMResendInterval').removeClass('error');*/

    $(this).removeClass('error');
    $("#requiredspan").hide("slow");

}

【问题讨论】:

    标签: jquery


    【解决方案1】:

    在事件中发送this 以了解谁调用了该函数:

    <input type="text" id="txtOMSourceName" onkeypress="hideSpan(this)"/>
    

    和功能:

    function hideSpan(e) {
     /*  $('#txtOMSourceName').removeClass('error');
         $('#ddlOMSite').removeClass('error');
         $('#txtMPName').removeClass('error');
         $('#txtOMResendInterval').removeClass('error');*/
    
        $(e).removeClass('error');
        $("#requiredspan").hide("slow");
    }
    

    【讨论】:

      【解决方案2】:

      我认为这是一个更好的解决方案:

      假设你有一堆文本输入:

      <input type="text" id="txtOMSourceName" />
      <input type="text" id="txtMPName "/>
      

      您可以在每个标记元素中编写一个函数,而不是:

      $('input[type="text"]').on('keydown', function() {
      
          $(this).removeClass('error');
          $('#requiredspan').hide('slow');
      }
      

      【讨论】:

      • 这个函数在JS文件中应该放在哪里?
      • 它可以去很多地方,但最安全的地方,因为我不知道你的脚本会在主层,在$(window).ready( function() { --the code-- });
      • JavaScript 运行时错误:对象不支持属性或方法'on' 代码:function $(document).ready(function () { $(function () { $("#tTypes") .tabs(); $('#divAddOMSource').dialog({ autoOpen: false, modal: true, width: 500, resizable: false, title: "OM source" }); $('#divAddEmailSource').dialog ({ autoOpen: false, modal: true, width: 500, resizable: false, title: "Email source" }); }); $('input[type="text"]').on('keydown', function () { $(this).removeClass('error'); $('#requiredspan').hide('slow'); }); });
      • 您有一个无关的函数:将其粘贴到: $(document).ready(function () { $("#tTypes").tabs(); $('#divAddOMSource').dialog ({ autoOpen: false, modal: true, width: 500, resizable: false, title: "OM source" }); $('#divAddEmailSource').dialog({ autoOpen: false, modal: true, width: 500,可调整大小:false,标题:“电子邮件来源”}); $('input[type="text"]').on('keydown', function () { $(this).removeClass('error'); $ ('#requiredspan').hide('slow'); }); });
      • 我仍然收到错误消息:JavaScript 运行时错误:对象不支持属性或方法 'on' 。这是一个带有 html 控件的 asp.net web 表单。我不知道这是否会导致问题。
      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      相关资源
      最近更新 更多