将参数传递给JQuery onclick事件


Passing Parameters to JQuery onclick event

我是Jquery的新手,需要正确的策略来执行动态表单。

我想创建一个动态表单。我从数据库中检索值,将它们显示为行&然后,对于每个值,用户可以添加任意多的行。下面的代码显示了一个循环,它为每个值创建一个表,ID为"customFields",并附加"$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…)吗?

我希望我能正确地解释这个问题。这个问题被问了很多次,但我是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。您还应该将HTML中的<a href="javascript:void(0)"替换为<a href="#"

Fiddle: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');
});

Demo(这将ID&total放入每行的第一个和第二个输入字段):http://jsfiddle.net/verashn/7HCZu/5/