2011-12-23 40 views
0

我的頁面上有2個按鈕。按鈕1正在執行javascript函數,另一個用於表單處理。的問題是,按鈕1被覆蓋按鈕的值和功能2.按鈕覆蓋/衝突在同一網頁上的另一個按鈕

按鈕1(未在一種形式)具有下列的HTML代碼:

<input id="show_hint" class="button" type="submit" value="Hint" onClick="location.href='#hint'" /> 

連接到它的JavaScript是:

// Button 1 
$(function(){ 
    var count = 3, 
     $btn = $('input[type="submit"]'); 
     $btn.val($btn.val()+' ('+count+')') 

    $btn.click(function(){ 
     $btn.val($btn.val().replace(count,count-1)); 
     count--; 
     $('#hintscore') 
     .hide() 
     .css({ 
      bottom: 30, 
      left: 300, 
      opacity: 1, 
     }) 
     .show() 
     .stop() 
     .delay(200) 
     .animate({'bottom':75, opacity: 0},1000); 

     if(count==0) { 
      return !$btn.attr('disabled','disabled'); 
     } 
    }) 
}); 

按鈕2(以一種形式)具有這樣的HTML代碼:

<input id="showmenu_win2" class="button" type="submit" value="Menu" /> 

JavaScript的阿塔因爲它是:

$('#form').submit(function() { 
     $.ajax({ 
      type: "POST", 
      data: $("#form").serialize(), 
      cache: false, 
      url: "insert.php" 
     }); 
     return false; 
    }); 

所以這兩個是相互衝突的,它與type =「submit」有關。但我該如何解決這個問題?

非常感謝

+0

它們是2種不同的形式還是相同的形式?如果你適當地包裝它們,那麼他們應該正確地將數據提交給它們各自的表格。如果你只是在尋找一個「按鈕」,那就改爲使用',它不應該提交表單或導致衝突。 – 2011-12-23 23:32:19

回答

1

您JS的這一部分:

$btn = $('input[type="submit"]'); 

是選擇這兩個按鈕,因此將相同的行爲附加到兩個按鈕。

既然你對每個按鈕的ID,您可以準確地通過ID選擇您需要的按鈕:

$btn = $("#show_hint"); 
+0

謝謝,這工作得很好!我認爲這與提交有關,從未考慮過使用ID的方式。... 也感謝所有其他人回覆! – Maurice 2011-12-24 10:11:08

1

$btn = $('input[type="submit"]');將選擇所有 DOM中提交的輸入元素(所以當你打電話$btn.click(...你基本上是結合此事件處理到這兩個提交按鈕的)。

既然你對每個按鈕的ID,您就可以改變:

$btn = $('input[type="submit"]'); 

要:

$btn = $('#show_hint'); 

您還可以找到一個根元素開始你選擇,讓你只選擇你想要的按鈕:

$btn = $('#ancestor-element').find('input[type="submit"]'); 

或者如果你想選擇所有除了一個形式210個元素:

$btn = $('input[type="submit"]').not($('#form').find('input[type="submit"]')); 
0

您可以通過定期<button>更換<input type="submit">。達到相同的目標。

你甚至可以用onclick事件創建一個<div>來模仿按鈕。您不限於input type="submit"

1

更改按鈕類型,以正常輸入按鈕而不是提交。通過選擇ID選擇器來更改腳本以將按鈕綁定到函數

在下面的代碼中,$("#show_hint")將返回輸入按鈕的對象,其ID爲show_hint

//按鈕1

HTML

<input id="show_hint" class="button" type="button" value="Hint" onClick="location.href='#hint'" /> 

腳本

$(function(){ 
    var count = 3, 
    $("#show_hint").val($(this).val()+' ('+count+')') 

$("#show_hint").click(function(){ 
    $("#show_hint").val($(this).val().replace(count,count-1)); 
    count-- 

// Your remaining code... 

對於第二按鈕

HTML

<input id="showmenu_win2" class="button" type="input" value="Menu" /> 

腳本

$('#showmenu_win2').click(function() { 
    $.ajax({ 
     type: "POST", 
     data: $("#form").serialize(), 
     cache: false, 
     url: "insert.php" 
    }); 
    return false; 
}); 
0

我不知道這是你want.My回答解決的辦法是設置顯示/隱藏按鈕爲type =「按鈕」,同時提交的類型=「提交」。 示例

<button id="hide" type="button" >Hide</button> 
<button id="show" type="button" >Show</button> 
相關問題