我正在尝试根据访问者的年龄显示不同的 iframe,而无需重定向/刷新。
但是在验证访问者年龄后,javascript 没有被正确应用,或者根本没有应用。
我总是以一个空白的 iframe 结束。 有人请看下面我的代码:
<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script></head>
<form method="post">
<input type="date" name="dob"><br>
<input type="submit" name="submit" value="Verify Age" />
</form>
<?php
$minAge = 18; // You might read this from a file/database.
$minAge *= 3600*24*365.25; // $minAge in seconds
if(isset($_POST['submit'])){
$birth_date = strtotime($_POST['dob']);
$now = strtotime("now");
$age = $now - $birth_date; // age is in seconds
if($age > $minAge)
echo '<script>$("#myiframe").attr("src", "http://URL1.com");</script>';
else
echo '<script>$("#myiframe").attr("src", "http://URL2.com");</script>';
} ?>
<iframe id="myiframe"></iframe>
</html>
最佳答案
你的 js 在 iframe
之前开火了被添加到 DOM 中。您可以在 echo
下移动您的 PHP 代码(至少是渲染,即 iframe
)标记或使用类似 $(document).ready(function(){<...>})
的东西.顺便说一句,还有一种更优雅的方式:
<?php
$minAge = 18; // You might read this from a file/database.
$minAge *= 3600*24*365.25; // $minAge in seconds
if(isset($_POST['submit'])){
$birth_date = strtotime($_POST['dob']);
$now = strtotime("now");
$age = $now - $birth_date; // age is in seconds
?>
<iframe id = "myiframe"
src = "<?php echo ($age > $minAge ? 'http://URL1.com' : 'http://URL2.com'); ?> ">
</iframe>
<?php } ?>
关于javascript - php 不是 "echo-ing"javascript 正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29480235/