JQuery如何使用</button> </form>之间的后代从<button>遍历<form>

时间:2012-11-15 04:39:28

标签: jquery forms button traversal descendant

我想知道,在JQuery中,如何在不使用id的情况下从选择器$('button')获取<form>元素? 我知道如何使用id来获取它,但不知怎的,我需要上面的方法。

我尝试alert($('button').parent().prev().get(0).nodeName)弹出FORM,这意味着我到了那里。但是,当我使用$('button').parent().prev().get(0).submit().serialize()或甚至.attr('name')时,它不起作用。

结构如下,我有10行<tr>......</tr>

<table>
    <tr><form name='form' method='POST' autocomplete='on'>
    <td id='df'><button type='button'>Go</button></td>
    <td><input type='reset' value='Clear'/></td>
    <td><input name='date'</td>
    <td><input name='customer'</td>
    .......
    </tr>
</table>

任何穿越专家都可以教我?谢谢=)

3 个答案:

答案 0 :(得分:0)

你有这个HTML:

<table>
<tr><form name='form' method='POST' autocomplete='on'>
<td id='df'><button type='button'>Go</button></td>
.......
</tr>
</table>

您认为这将产生:

<table>
  <tr>
    <form>
      <td>
        <button/>
      </td>
    </form>
  </tr>
</table>

然后$(...).closest('form')可能是所需的遍历方法。

Google Chrome就是这样生产的;它将表单视为行标题(http://jsfiddle.net/UULtc/):

<table>
  <tr>
    <form/>
    <td>
      <button/>
    </td>
  </tr>
</table>

然后您可以将表单作为$(...).closest('tr').find('form:first')访问,但表单不会包含其预期的输入,所以要小心。

您需要更改HTML(如果只有一行,只需将表格包装在表格周围)。如果您要坚持使用表格,您可能还需要更改javascript。这是一个想法(未经修改,未经测试):

$('table button').click(function(){
  $(this)
    .closest('table')
    .find('tr')
    .not($(this).closest('tr'))
    .find('input')
    .attr('disabled', 'disabled')
  ;
});

答案 1 :(得分:0)

将您的HTML更改为此,然后尝试。

<form name='form' method='POST' autocomplete='on'>
<table>
    <tr>
       <td id='df'><button type='button'>Go</button></td>
       <td><input type='reset' value='Clear'/></td>
       <td><input name='date'</td>
       <td><input name='customer'</td>
    .......
   </tr>
</table>
</form>

答案 2 :(得分:0)

我认为我是因为.get()方法返回一个节点,因此您无法在其上调用jQuery方法,例如.submit().attr()

由于您只获得一个元素,因此在提交或获取name属性之前,我认为您不需要使用.get()方法。

$('button').parent().prev().attr('name')实际上给了我表格的名称。