如何在jQuery中获取元素的形式

How to get the form of an element in jQuery

本文关键字:元素 获取 jQuery      更新时间:2023-09-26

我有一个javascript函数,可以很好地从html 运行

'onClick="my_function(this.form)"

但如果表单中的特定元素键入了数据,我也想调用此函数。我尝试过

  jQuery(document).ready(function($){
   $('#option_field_bizpostcode').keyup(function() {
      var myform = $(this).closest('form').options-i-have-tried();
      my_function(myform);
        });
 });

选项-i-have-tried()包括html()(这表明我在正确的表单ok中有html),
get()有点暗箭伤人,
serializeArray()从类似问题的一些答案中,
什么都没有。

在每种情况下,我的函数都抱怨它的参数形式,或者更具体地说,form.myelement是未定义的

非常感谢

将FORM元素传递到内联处理程序(onclick属性)中的函数中,因此需要对jQuery处理程序执行同样的操作。

jQuery(document).ready(function($){
    $('#option_field_bizpostcode').keyup(function() {
        var myform = $(this).closest('form')[0]; //because the form element is at the first index in the jquery object
        my_function(myform);
    });
});

或者更好的是,你为什么不坚持这样做呢:

jQuery(document).ready(function($){
    $('#option_field_bizpostcode').keyup(function() {
        my_function(this.form);
    });
});

我认为您应该传递myform而不是form

jQuery回调中的

this将是附加处理程序的元素。它是本机DOM元素,没有任何jQuery包装器。

因此,假设#option_field_bizpostcode是一个表单元素,您应该能够像在onclick方法中那样执行this.form

my_function(this.form);

我认为如果您使用closest调用中的第一个元素,您将成功:

$('#option_field_bizpostcode').keyup(function() {
  var myform = $(this).closest('form')[0];
  my_function(myform);
});