代码看起来像这样:
<?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);
}
";
关于javascript - 3层嵌入引号,JS函数不注册变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755372/