简体   繁体   中英

Echo php variable to javascript doesn't work

I'm trying to echo PHP variable within the javascript code, but it's not working.

I would like to get the position from the top of the link identified by id and then alert it. When I type "#edit5" in the brackets of document.querySelector() it works fine. The position form the top is alerted. But if instead of typing "#edit5" I use PHP echo, I got error that document.querySelector is NULL. However, when I check the code the string which was displayed by PHP is "#edit5". So it should work. But it doesn't. Does any one know how can I make it working?

<?php $edit = "#edit" . $_GET['edit']; ?>

<script>
var position= document.querySelector("<?php echo $edit; ?>").getBoundingClientRect().top;
alert(position);
</script>
<?php $edit = "#edit" . $_GET['edit']; ?>
<html>
<head>
<title>The title</title>
</head>
<body>
<div id="edit5">Edit5</div>
<script>
  var position = document.querySelector("<?php echo $edit; ?>").getBoundingClientRect().top;
  alert(position);
</script>
</body>
</html>

Wrap your script in an html context, and the alert will pop-up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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