我是Jquery的新成員,需要正確的策略來執行動態表單。將參數傳遞給JQuery onclick事件
我想創建一個動態表單。我從數據庫中檢索值,將它們顯示爲行&,然後對於每個值,用戶可以根據需要添加任意數量的行。下面的代碼顯示了一個爲每個值創建一個表的循環,其中帶有「customFields」ID,它附加了「$ i」變量以使其唯一。
// query code
$i = 1;
while ($row = mysql_fetch_array($sqlQ))
{
$var1 = $row['sid'];
$var2 = $total_rows;
?>
<table id="customFields<?php echo $i; ?>" class="box-table-a" align="left">
<thead>
<tr>
<th colspan="5" scope="col"><?php echo $row['VS_NAME']; ?></th>
<th scope="col" align="Right"><a href="javascript:void(0)" id="addCF<?php echo $i++; ?>" >Add Row</a></th>
</tr>
</thead>
</table>
}
現在爲這個代碼,我寫了下面的JavaScript代碼追加。
<script>
<?php for ($i = 1; $i <=5; $i++) { ?>
$("#addCF"+<?php echo $i; ?>).click(function(){
$("#customFields<?php echo $i;?>").append('<tr ><td width="13%"><input type="text" name="godkant[]" class="fieldWidth" /></td><td width="11%" style="background:#b5dbe6" ><input type="text" name="foreRengoring[]" class="fieldWidth" /></td><td width="12%" style="background:#e6b8b8" ><input type="text" name="efterRengoring[]" class="fieldWidth" /></td><td width="12%" style="background:#c0d498" ><input type="text" name="borvarden[]" class="fieldWidth" /></td><td width="12%" style="background:#ffff66" ><input type="text" name="injust[]" class="fieldWidth" /></td><td width="40%" ><input type="text" name="noteringar[]" class="fieldWidthNote" /></td></tr>'); });
<?php } ?>
</script>
上面的代碼工作得很好。但我不知道我的PHP while循環將返回的值的數量。所以我需要傳遞兩個值到這個JavaScript點擊事件。一個用於循環,第二個用於添加一行時顯示。
問題; 1.執行這種功能的最佳策略是什麼? 2.我可以在我自己的函數中使用Jquery事件處理程序(如果我正確調用它 - $(#id).append ...),可以在Onclick事件上調用它嗎?
我希望我解釋正確的問題。 這個問題被問了很多次,但我是Jquery的新手,這就是爲什麼我無法將答案映射到我的解決方案。
需要幫助。
謝謝
另外:由於您的附加HTML相當長且難以管理,因此添加它的更好方法是將其放入'script'標記在你的HTML中,然後使用jQuery來包含內容。演示:http://jsfiddle.net/verashn/7HCZu/3/ – VLS
感謝您的標準方式來做到這一點。但這並沒有解決我的問題。我有兩個值從我的php代碼[主代碼,而不是我在JavaScript中使用的],我想在附加行(在輸入字段中)硬編碼,我該怎麼做 – Adil
你傳遞了哪些值?我只看到當前正在使用的'$ i'。 – VLS