简体   繁体   English

有没有办法在JavaScript函数中包含PHP值?

[英]Is there a way to include PHP value inside a javascript function?

I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script. 我想动态地告诉javascript隐藏哪个<div> ,但是我不知道如何将请求发送到javascript,因为它是客户端脚本。

for eg: 例如:

<?
$divtohide = "adiv";
?>
<script language="javascript">
            function hidediv($divtohide) {
            ................
            }
</script>

Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal: 假设$divtohide实际上包含一个<div>元素的ID而不是一个JavaScript变量名,请照常编写JavaScript函数:

function hidediv(divtohide) {
    // Your code may differ here, mine's just for example
    document.getElementById(divtohide).style.display = 'none';
}

And print out the PHP variable only when you're calling it, within a pair of quotes: 并且仅在调用时以双引号将PHP变量打印出来:

hidediv("<?php echo addslashes($divtohide); ?>");

addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break. addslashes()确保变量中的引号"被转义,以使您的JavaScript不会中断。

as BoltClock wrote, use php to pass the variable. 正如BoltClock所写,请使用php传递变量。

but you can do it by most simple way, just write hidediv("<?=$divtohide?>") 但是您可以通过最简单的方法来做到这一点,只需编写hidediv("<?=$divtohide?>")

<script type="text/javascript">

function hidediv() {

    divobj = document.getElementById('<?= $divtohide ?>');

    divobj.style.display = 'none';

}

</script>

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

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