繁体   English   中英

如何在PHP echo函数内插入javascript?

[英]How can i insert javascript inside a PHP echo function?

我将按钮插入到回显中时无法单击按钮。

echo '<input onclick="window_target = document.basicForm.maparea1; 
                      window_name = window.open("search.php", 
                                                "window_name",
                                                "resizable=0,location=0,directories=0,status=0,top=30,left=100,toolbar=no,width=180,height=480,menubar=no,scrollbars=no"
                                                );
                      window_name.window_target = window_target
                     " value="Select" type="button">';

欢迎使用现代JS:请尽量不要使用onclick ,或者实际上不使用任何直接嵌入HTML的on...处理程序。 而是,生成您的页面来执行以下操作:

<!doctype html>
<html>
  <head>...</head>
  <body>
    <input type="..." id="spawnClickerThing" ...>
    ...
    <script src="mypagescript.js"></script>
  </body>
</html>

(因此不进行PHP echo / printed!),然后在该javascript中包含所有事件绑定等:

...
function newWindowHandling(avt) {
  var window_target = document.basicForm.maparea1;
  var window_name = window.open("search.php", "window_name", "...");
  window_name.window_target = window_target;
}

function setEverythingUp() {
  document.removeEventListener("DOMContentLoaded", setEverythingUp);      

  var inputclicker = document.querySelector("#spawnClickerThing");
  inputclicker.addEventListener("click", newWindowHandling);
}

document.addEventListener("DOMContentLoaded", setEverythingUp);

根据您是否使用库来获得更有效的JavaScript,可以压缩该代码,但总的原则仍然适用。 不要使用PHP来“内联”注入JS,它非常脆弱且无法维护。 将脚本保存在易于编辑的.js文件中,而与为页面生成HTML源代码的.php脚本无关。

转义报价

echo '<input onclick="window_target = document.basicForm.maparea1; window_name = window.open(\'search.php\', \'window_name\', \'resizable=0,location=0,directories=0,status=0,top=30,left=100,toolbar=no,width=180,height=480,menubar=no,scrollbars=no\'); window_name.window_target = window_target" value="Select" type="button">';

您不能以这种方式工作,必须使用

您必须在javascript中使用此代码。我假设您已包含jquery

$(document).on('click', '.btninline' ,function() {
window_target = document.basicForm.maparea1; 
window_name = window.open("search.php", "window_name","resizable=0,location=0,directories=0,status=0,top=30,left=100,toolbar=no,width=180,height=480,menubar=no,scrollbars=no"); 
window_name.window_target = window_target;
}

然后在你的PHP中

echo '<input class="btninline" value="Select" type="button">';

暂无
暂无

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

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