2011-02-28 50 views
0

我有一堆鏈接ID爲1 - n,我想通過該ID到我的窗體中的隱藏輸入(我有很多鏈接,但只想要一個窗體而不是爲每個ID生成數千行額外的HTML表單)。將值傳遞給隱藏的輸入與jQuery

鏈接看起來是這樣的:

<a href='javascript:$("#removeSave").submit()' id="n">Remove</a> 

採用隱藏式輸入的形式如下:

<form action="/php/removeSave.php" method="POST" id="removeSave"> 
    <input type="hidden" name="ID" value=""/> 
</form> 

任何幫助嗎?

+4

給出的鏈接似乎沒有ID。此外,爲了清楚起見,ID不能以數字開頭。 – kojiro 2011-02-28 02:22:06

+0

對不起,添加了鏈接ID。 – AKor 2011-02-28 02:30:31

回答

2

這個設置隱藏input與ID IDa元素的id值它提交form之前。

<a href='#' id='n' onclick='$("#ID").val(this.id);$("#removeSave").submit();'>Remove</a> 


<form action="/php/removeSave.php" method="POST" id="removeSave"> 
    <input type="hidden" name="ID" id="ID" value=""/> 
</form> 
+1

根據ISO8879(參見http://www.w3.org/TR/html4/types.html#h-6.2),ID屬性必須以字母開頭(並且所以'... id =「123 「......」是無效的,當然,你可以用「id」或其他東西加前綴,然後用'this.id.replace(/ \ D/g,「」)'數字字符出來。 – 2011-02-28 02:59:07

0

您沒有提供的「刪除」鏈接,其中ID會被注意到的完整的上下文,所以我會假設的格式,你可以從那裏適應。

<!-- HTML //--> 

<!-- Format for Each Element. "123" is the ID here //--> 
<div id="element123"> 
    This is Element 123 (ID#123) 
    <a href="/php/removeSave.php?ID=123">Remove</a> 
</div> 

<!-- The Form at the Bottom of the Page //--> 
<form id="removeSave" method="POST" action="/php/removeSave.php"> 
    <input type="hidden" name="ID" value="" /> 
</form> 

jQuery的段這種方法的

<script type="text/javascript"> 
$(document).ready(function(){ 

// Clicks of Links starting with "/php/removeSave.php?ID=" 
    $('a[href^="/php/removeSave.php?ID="]').click(function(e){ 
    // Don't let the Link act as a basic link 
    e.preventDefault(); 
    // Get the Link HREF attribute 
    href = $(this).attr('href'); 
    // Derive the Form ID and ID Value 
    bits = href.match(/^\/php\/([^\.]+)\.php\?ID=(\d+)/); 
    formID = bits[1]; 
    elementID = bits[2]; 
    // Set the Field Values and Submit the Form 
    $form = $('#'+formID); 
    $form.find('input[name="ID"]').val(elementID); 
    $form.submit(); 
    }); 

}); 
</script> 

好處?

優雅的降級 - 只要你的PHP腳本也可以處理GET變量,如果這個頁面是從沒有啓用Javascruipt的瀏覽器加載的,或者無法加載jQuery,點擊「刪除」鏈接仍然會執行預期的操作。

機遇AJAX-ification - 而不是.click(function(e){段內的所有這些其他操作,您可以使用jQuery的$.post()功能和鏈接的HREF的查詢字符串段直傳球此請求處理程序和操作頁面,而無需做一個完整的頁面重新加載。