2013-04-10 92 views
0

我試圖找出一種方法來驗證一個按鈕被點擊的ID,並不存在於一組輸入中。從按鈕獲取ID比較輸入值與單一值

代碼點擊的檢查ID

$(".detail-view button").on("click", function() { 
     var detailID = $(this).attr('id'); 

代碼不存在

function itemExists() { 
    $("input#lunchorder_item_entry_id").each(function() { 
     existingID = $(this).val(); 

     if(detailID == existingID) { 
      alert("You have already added this item. If you want to change item details, please remove the item and re-add it to your cart. Thank You!"); 
     } else { 

     } 
    }); 
} 

我在此只能部分時間的問題,如果任何人有建議更好的方法來做到這一點我相信這不是實現我的目標的最佳方式。謝謝!

+2

有一個範圍的問題,'detailID'是不是在你的代碼中的全局變量。在'itemExists'函數的上下文中,通過這種方式將''this(this).attr('id');''轉換爲'this.id' – undefined 2013-04-10 21:37:57

+0

並將其轉換爲jQuery對象直接訪問'id'屬性,而不是通過一個函數訪問它。 – fernandosavio 2013-04-10 22:10:01

+0

好吧,我應該提到'itemExists'函數在我的點擊函數中。 – philecker 2013-04-10 22:22:46

回答

0

detailID在您的itemExists()函數中不可見,或者使其成爲全局函數,或者將其傳遞給函數。

itemExists(detailID){ 
    // if(detailID == existingID) { 
} 

整個這應該是這個樣子

$(".detail-view button").on("click", function() { 
     var detailID = $(this).attr('id'); 
     itemExists(detailID); 
}); 
function itemExists(detailID) { 
    $("input#lunchorder_item_entry_id").each(function() { 
      var existingID = $(this).val(); 
      if(detailID == existingID) { 
       alert("You have already added this item. If you want to change item details, please remove the item and re-add it to your cart. Thank You!"); 
      } else { 

      } 
    }); 
} 
+0

這並不能真正解決我的問題,因爲它仍然允許其他事情發生。我想我真正需要的是一種將每個值與數組進行比較的方法。 – philecker 2013-04-11 13:13:50