jQuery:如何獲取表單提交時點擊了哪個按鈕? - jQuery: how to get which button was clicked upon form submission?

問題:

I have a .submit() event set up for form submission.我爲表單提交設置了一個.submit()事件。 I also have multiple forms on the page, but just one here for this example.我在頁面上也有多個表單,但在此示例中只有一個表單。 I'd like to know which submit button was clicked without applying a .click() event to each one.我想知道在沒有對每個提交按鈕應用.click()事件的情況下點擊了哪個提交按鈕。

Here's the setup:這是設置:

<html>
<head>
  <title>jQuery research: forms</title>
  <script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
  <script type='text/javascript' language='javascript'>
      $(document).ready(function(){
          $('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
      });
      function process_form_submission( event ) {
          event.preventDefault();
          //var target = $(event.target);
          var me = event.currentTarget;
          var data = me.data.value;
          var which_button = '?';       // <-- this is what I want to know
          alert( 'data: ' + data + ', button: ' + which_button );
      }
  </script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
  <input type='hidden' name='data' value='blahdatayadda' />
  <input type='submit' name='name1' value='value1' />
  <input type='submit' name='name2' value='value2' />
</form>
</body>
</html>

Live example on jsfiddle jsfiddle 上的實時示例

Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?除了在每個按鈕上應用 .click() 事件之外,有沒有辦法確定點擊了哪個提交按鈕?


解決方案:

參考一: https://en.stackoom.com/question/O0Ts
參考二: https://stackoom.com/question/O0Ts
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章