![](/img/trans.png)
[英]how to passing parameters in javascript onClick event using Jquery?
[英]Passing Parameters to JQuery onclick event
我是Jquery的新手,需要正确的策略来执行动态表单。
我想创建一个动态表单。 我从数据库中检索值,将它们显示为行然后对于每个值,用户可以根据需要添加任意数量的行。 下面的代码显示了一个为每个值创建一个表的循环,带有“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的新手,这就是为什么我无法将答案映射到我的解决方案。
需要帮忙。
谢谢
在这种情况下,您的jQuery中不需要PHP。 你可以像这样重构它:
$('.box-table-a a').click(function (evt) {
evt.preventDefault();
$(this).parents('table').append(rowHtml);
return false;
});
其中rowHtml
是您要添加的HTML。 如果您计划每个表有多个链接,则应该为添加链接分配一个类(例如, add-link
),然后您的事件监听器变为$('.add-link').click
。 您还应该使用<a href="#"
替换HTML中的<a href="javascript:void(0)"
<a href="#"
。
小提琴: http : //jsfiddle.net/verashn/7HCZu/
编辑
要将其他数据传递到您的行,请将数据放在table
元素中,如下所示:
<table ... data-rowid="<?php echo $var1; ?>" data-total="<?php echo $var2; ?>">
然后用jQuery读取它:
$('.box-table-a a').click(function (evt) {
...
var rowId = $(this).parents('table').data('rowid');
var total = $(this).parents('table').data('total');
});
演示(这会将ID和总数放入每行的第一个和第二个输入字段): http : //jsfiddle.net/verashn/7HCZu/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.