代码看起来像这样:

<?php
 $page->startscript();
  echo "
    function f1(id){
        $('#def').html('<button class=\'btn btn-danger\' onclick=\'f2(id);\'>act</button>');
    }
    function f2(id){
        alert(id);
    }
  ";
 $page->endscript();
?>


startscript()endscript()可以正常工作,它只允许我向页面添加JS。不起作用的是id不会从f1传递到f2,它只是返回空白。我认为这与引号有关,而不是被视为变量。如果我将int用作onclick属性的参数,则可以正常工作。

最佳答案

不会在Javascript的字符串内部扩展变量(ES6添加了“模板字符串”,支持此功能),您需要使用串联。并假设id是字符串,则需要在函数调用中用引号引起来。

   echo"
      function f1(id){
          $('#def').html('<button class=\'btn btn-danger\' onclick=\'f2(\"' + id + '\");\'>act</button>');
      }
      function f2(id){
          alert(id);
      }
      ";

09-20 16:49