[英]how to add jquery toggle between smarty loop or foreach items
對於jQuery大師在那里,我正在嘗試。 我試圖在smarty模板{foreach項目列表}之間添加一個jquery切換,我的代碼很好用,因為它可以在第一個列表項目上使用,當我單擊列表中的第2個,第3個等項目時,它不會切換。 有什么建議么?
jQuery代碼
<script>
$(function(){
$("#itm_add").each(function(){
$(this).click(function(e){
e.preventDefault();
$("#itm_add_box").parent("tr").empty();
href=$(this).attr("href");
$(this).closest("tr").next("tr").empty().append('<td colspan="6"><div
id="itm_add_box" data-href="'+href+'">
<input type="text" id="itm_serial" class="input" placeholder="Serial
Number..." />
<input type="text" id="itm_qty" class="input"
placeholder="Quantity..." />
<button class="green" id="itm_submit">Submit</button></div><td>');
$("#itm_add_box button").click(function(e){
e.preventDefault();
href2=$(this).parent("#itm_add_box").attr("data-href");
serial=$(this).parent().find("#itm_serial").val();
qty=$(this).parent().find("#itm_qty").val();
href2=href2+"&item_serial="+serial+"&item_quantity="+qty;
window.location=href2;
});
});
});
});
</script>
Smarty模板:
<table>
<tr>
<td class="olohead" align="center" width="80">ID</td>
<td class="olohead" align="center">Type</td>
<td class="olohead" align="center">Name</td>
<td class="olohead" align="center">No</td>
<td class="olohead" align="center">Features</td>
</tr>
{foreach from=$customer item=customer}
<td class="olotd4" nowrap align="center">{$customer.ID}</td>
<td class="olotd4" nowrap align="center">{$customer.TYPE}</td>
<td class="olotd4" nowrap > {$customer.NAME} </td>
<td class="olotd4" nowrap > {$customer.NO} </td>
<td class="olotd4" nowrap align="center">
<a id="itm_add">Add</a>
</td>
</tr>
{/foreach}
</table>
再次:這有效,只是該切換僅適用於列出的第一個項目。 有什么建議么?
在注釋中已經提出了從循環中刪除id
並將其放入類的建議。 考慮到這一點,我嘗試清理一下您的js:
$(function() {
$(".itm_add").click(function(e) {
e.preventDefault();
$(this).parent("tr").empty();
$(this).closest("tr").next("tr").empty().append(getTemplate($(this).attr("href")));
$(this).find("button").click(function(e) {
e.preventDefault();
var href = $(this).parent("#itm_add_box").attr("data-href");
var serial = $(this).parent().find("#itm_serial").val();
var qty = $(this).parent().find("#itm_qty").val();
href += "&item_serial=" + serial + "&item_quantity=" + qty;
window.location = href;
});
});
});
function getTemplate(href) {
return '<td colspan="6">'
+ '<div id="itm_add_box" data-href="' + href + '" >'
+ '<input type="text" id="itm_serial" class="input" placeholder="Serial Number..." /> '
+ '<input type="text" id="itm_qty" class="input" placeholder="Quantity..." /> '
+ '<button class="green" id="itm_submit">Submit</button>'+
+'</div>'
+ '<td>';
}
請注意,此代碼未經測試,因此其中可能存在錯誤...
我改變了什么:
.each
因為它不是必需的。 jQuery將在選擇器適用的所有元素上自動添加事件處理程序。 $(this)
,以使代碼僅應用於觸發事件的項目,而不是所有匹配的項目。 var
關鍵字,使所有變量的功能范圍不再是全局的。 讓我知道是否遺漏了任何錯誤,或者是否需要進一步說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.