将字符串作为参数传递给函数onclick event jquery

Pass a string as a parameter to a function onclick event jquery

本文关键字:函数 onclick event jquery 参数传递 字符串      更新时间:2023-09-26

我想寻求帮助,因为我在使用for创建按钮时遇到问题,并在onclick中输入带有参数的函数的名称,但此参数是一个字符串,我得到一个数组,循环结束时,所有按钮都有数组最后一个元素的名称,而不是数组的每个位置。。提前感谢你的帮助。。

    <!DOCTYPE html>
 <html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
 <script>
 function enviar(periodo){
 alert(periodo);
 }
 </script>
 </head>
 <body>
 <?php
 $formatos=
  array(array('idPeriodo'=>'pp2019'),
      array('idPeriodo'=>'pp2018'),
      array('idPeriodo'=>'pp2017'),
      array('idPeriodo'=>'pp2016'));
  for($l=0; $l< count($formatos); $l++){
 ?>
  <button onclick="enviar(<?php echo json_encode($formatos[$l]['idPeriodo'])?>)">Guardar</button>
<?php
      }
?>
</body>
</html>

您已经有了一个PHP循环,所以javascript位是无用的。试试这个:

<?php     
for($l=0; $l< count($formatos); $l++){
    $per = json_encode($formatos[$l]['idPeriodo']);
?>
<button onclick="enviar('<?= $per ?>')">Guardar</button>
<?
}
?>

您想要它json_encode有什么原因吗?这是有效的。试试这个:

编辑

 <?php
   $formatos=    
   array(array('idPeriodo'=>'pp2019'),
   array('idPeriodo'=>'pp2018'),
   array('idPeriodo'=>'pp2017'), 
   array('idPeriodo'=>'pp2016'));

    for($l=0; $l< count($formatos); $l++){   

    $periodo = $formatos[$l]['idPeriodo'];        
   ?>
     <button onclick="enviar('<?php echo $periodo; ?>')">Guardar</button>      
   <?php
      }   
   ?>

您得到数组的最后一个元素,因为您每次都重新定义per变量。使用此代码:

<?php
$formatos=
    array(array('idPeriodo'=>'pp2019'),
          array('idPeriodo'=>'pp2018'),
          array('idPeriodo'=>'pp2017'),
          array('idPeriodo'=>'pp2016'));
for($l=0; $l< count($formatos); $l++){
    $param = json_encode($formatos[$l]['idPeriodo']);
    $param = addslashes($param);
    ?>
          <button onclick="enviar(<?php echo $param; ?>)">Guardar</button>
          <?php
          }
?>

试试这个脚本,希望它能起作用:

<?php
$formatos = array(
    array('idPeriodo'=>'pp2019'),
    array('idPeriodo'=>'pp2018'),
    array('idPeriodo'=>'pp2017'),
    array('idPeriodo'=>'pp2016')
);
for($l = 0; $l < count($formatos); $l++) {
?>
<button onclick='enviar(<?php echo json_encode($formatos[$l]['idPeriodo']);?>)'>Guardar</button>
<?php } ?>