【问题标题】:Getting the actual id from where slector works on multiple id从选择器在多个 id 上工作的地方获取实际 id
【发布时间】:2016-10-26 12:15:21
【问题描述】:

我正在使用 jQuery。我有一个 Javascript 方法,它适用于这样的两个选择器 -

$('#from1, #form2').submit(function() {
   ....
   .... 

  //is there any way to know the actual id (that is - form1 or form2)
  //for which the submit() method is called
}

这是一个相当大的方法,其中两个表单(form1from2)共享几乎相同的代码,因此我不想分别为每个表单编写多个 submit() 方法。那么有什么方法可以获取调用submit 方法的实际id

【问题讨论】:

    标签: javascript jquery forms form-submit


    【解决方案1】:

    假设<form> 元素是匿名方法中的this,因为它们看起来来自您(非常精简的)发布的代码,那么您可以简单地使用:

    $('#form1, #form2').submit(function(){
      let formID = this.id;
    
      // or (expensively, redundantly):
      // formID = $(this).prop('id');
      // or:
      // formID = $(this).attr('id');
    });
    

    但是,如果 <form> 的子元素是 this,那么您可以改为使用:

    $('#form1, #form2').submit(function(){
      let formID = this.form.id;
    });
    

    请注意,在上面我已经更正了我认为是选择器中的错字,#from1 已更改为 #form1

    此外,正如 cmets 中正确指出的那样,let 是一种相对较新的 ES6 替代方法,用于声明变量;如果您需要支持旧版浏览器,您可能不得不坚持使用var

    【讨论】:

    【解决方案2】:
    $(this).attr('id')
    

    $(this) 将指向触发submit 事件的form

    这是所有事件处理程序中的通用语法。 this 将指向触发事件的元素,$(this) 将使其成为 JQuery 对象,以便您可以在其上使用许多内置的 JQuery 语法,就像我们使用 .attr('id') 的方式一样

    【讨论】:

      猜你喜欢
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      相关资源
      最近更新 更多