如何在php的echo中调用jquery脚本

在下面的代码中我想插入一个jquery脚本:我已经在代码中提到了我要插入jquery代码的空间:

<?php $no = 1; $total = 0; while ($row = mysqli_fetch_array($query)) { $stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']); echo ' '.$no.' '.$row['student_id'].'  '.$row['student_name'].'  '."".' '."".' Here i want to add jquery script     '; $total += $row['stu_id']; $no++; } ?> 

JQuery脚本如下: –

  var SecondNumVal = "20"; function ShowPercentage() { var $inputs = $('input'); // get values var firstNumVal = $inputs.eq(0).val(); // compute something var percentVal = (firstNumVal / SecondNumVal) * 100; // set value $inputs.eq(1).val(parseInt(percentVal) + '%').prop('readonly', true); } $(document).ready(function() { $('#mysecondnumber').on('change blur', ShowPercentage); });  

php将在呈现页面之前执行。 Jquery只在页面呈现后才有角色。 如果要为每个字段添加自定义函数,请使用类并选择该类的所有元素并在那里执行操作。 您可以在页面中的任何位置编写脚本,它将被执行。 无需添加到需要执行的位置。

正如其他答案所指出的那样,您不需要在每一行中包含脚本以使其工作。 另外,正如我在评论中提到的, $inputs指的是整个文档中的输入,而不是每个tr ,即使它确实如此, $inputs.eq(0)也会引用行中的第一个input ,这是student_id 。 简化示例(为input添加新类并将更改百分比添加到type="text" ),您只需在$.ready上调用此脚本

 // Delegate on the table to listen for changes in obtmark fields. // Less event listeners to attach $('#marks').on('change', '.obtmark', function() { var SecondNumVal = "20"; $mark = $(this) var firstNumVal = $mark.val(); // Find the tr this control is in and the corresponding percentage field $pct = $mark.closest('tr').find('.percentage') percentVal = (firstNumVal / SecondNumVal) * 100 pct = parseInt(percentVal) + '%'; $pct.val(pct).attr('readonly', true); });