我想检查父元素的 id,以显示图像的大版本或小版本。
<div id="content">
<?php include 'test.php';?>
</div>
<div id="sidebar">
<?php include 'test.php';?>
</div>
在 test.php 中,if 语句检查父级是否具有所需的 id。 有没有一种方法可以在不使用 JavaScript 的情况下获取父节点 ID?
最佳答案
没有。 PHP 对呈现的页面不执行任何操作。 但为什么不创建一个函数并使用参数调用它呢?
include 'test.php'
?>
<div id="content">
<?php showImage(); ?>
</div>
<div id="sidebar">
<?php showImage(true); ?>
</div>
<?php
在 test.php 中
function showImage($smallImage = false) {
if (!$smallImage) {
echo '<img src="path/to/bigimage" alt="" />';
} else {
echo '<img src="path/to/smallimage" alt="" />';
}
}
或者还有另一种方法。在包含文件之前设置一个变量,当您想要显示图像时,可以在 test.php 中设置 if 条件。
<div id="content">
<?php
$parentNode = 'content';
include 'test.php'
?>
</div>
<div id="sidebar">
<?php
$parentNode = 'sidebar';
include 'test.php'
?>
</div>
关于javascript - PHP 相当于 JavaScript 的parentNode 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26798402/