繁体   English   中英

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

[英]Pass a string as a parameter to a function onclick event jquery

我想寻求帮助,因为我在使用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>

您得到数组的最后一个元素,因为per都重新定义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循环,因此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
      }   
   ?>

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

<?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 } ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM