2011-11-30 30 views
18

提交按鈕,我點擊一個使用此提交按鈕:點擊一個特定的jQuery

$('input[type=submit]').click(); 

的問題是,我有更多的1提交我的網頁上的按鈕,所以我需要針對特定​​的提交按鈕。

我該怎麼做?

回答

23

如果您知道submit輸入的數量以及您想要觸發click的哪一個(按順序),則可以使用nth-child()語法來定位它。或者爲每個人分別添加一個ID或一個類。

選擇通過其索引的元素:

$('input[type="submit"]:nth-child(1)').trigger('click');//selects the first one 
$('input[type="submit"]:nth-child(2)').trigger('click');//selects the second one 
$('input[type="submit"]:nth-child(100)').trigger('click');//selects the 100th one 

實際上,有幾種方法可以做到這一點,包括使用.eq()http://api.jquery.com/eq

選擇通過其ID的元素:

<input type="submit" id="submit_1" /> 
<input type="submit" id="submit_2" /> 
<input type="submit" id="submit_100" /> 

<script> 
$('#submit_100').trigger('click'); 
</script> 

.click().trigger('click')的簡稱。

+0

有什麼理由去喜歡手寫'.trigger( '點擊')'在速記? – AntonChanning

+1

@AntonChanning它比其他任何東西都更受歡迎。速記函數是包裝器,所以調用它們時會有很小的開銷,但我無法想象它會有什麼值得注意的影響。我喜歡'.trigger('click')'形式更具描述性,因爲我更容易快速閱讀代碼。 – Jasper

+0

我猜它也可以作爲可用於任何類型事件(包括自定義事件類型)的語法的視覺提醒。 – AntonChanning

4

id s添加到每個按鈕並使用jQuery選擇id

或者,如果形式有id s,則只是針對表單並提交它像這樣:如果你添加標記,就像一個特定的id或class您input

$("#form-id").submit(); 
6

,可以使您的選擇器更具體。例如,如果你給的按鈕,你想要的form-btn這樣的ID:

<input type="submit" id="form-btn" /> 

你可以選擇像這樣:

$('input[type=submit]#form-btn').click(); 

或者只是:

$('#form-btn').click(); 
1

路遲到了,但如果你的提交按鈕有名字:

$("input[name='submitbuttonname']").click(); 
0

嗯它不能與此嚮導的形式工作intacted

$("#renqform").validate().settings.ignore = ":disabled"; 
return $("#renqform").valid(); 
1

另外一個建議!

我有一個表單,有多個提交,也有不同的價值屬性,所以我不能簡單地提交表單後,我執行我的內置確認。

取而代之,我添加了一些隱藏的按鈕,在我確認後得到一個Yes後,我強制點擊。

下面是按鈕:

<button id="email" name="email" type="submit" class="submit radius confirmation" value="all"><?php echo $this->__('Email Receipts to Selected'); ?></button> 
<button id="email-french" name="email-french" type="submit" class="submit radius confirmation" value="all"><?php echo $this->__('Email French Receipts to Selected'); ?></button> 
<button id="helper-email" name="email" type="submit" class="submit hide" value="all"></button> 
<button id="helper-email-french" name="email-french" type="submit" class="submit hide" value="all"></button> 

而這裏的jQuery的:

<script type="text/javascript"> 
jQuery(function ($) { 
    $('[id^=email]').on('click', function (e) { 
     e.preventDefault(); 

     var button = $(this); 

     notify.confirm(<?php echo json_encode($this->__('Are you sure?')); ?>, function (ans) { 
      if (ans) { 
       $('#helper-' + button.attr('id')).click(); 
      } 
     }); 
    }); 
}); 
</script>