我正在开发 Web 应用程序并且正在进行一些重构。
这样做,无论如何,我陷入了两难境地:我的页面中有一些相似或相同的部分,我想将它们压缩成一个,以便只进行一次编辑,因为编辑变得很痛苦。
但是怎么做呢?我正在使用 php、js 和 jquery。
用 php echos 做它是一个很大的不;管理所有括号真的很困难,而且在我看来这不是最优雅的解决方案,另外,我需要对打印的内容进行一些控制。
我在想一些关于函数的事情,但由于我没有太多经验,所以我真的不知道我在哪里可以碰到我的头。提前谢谢你。
编辑:有人问我一些例子。
<form action="insert.php" method="POST" class="big" style="display:none;">
<h3> Insert Contact </h3>
<fieldset class="col2">
<!-- Some inputs here -->
</fieldset>
<div>
<input type="submit" value="Send">
<input type="reset" value="Clean Form">
</div>
<input type="text" name="insert" value="1" style="display:none;">
<input type="text" name="modify" value="1" style="display:none;">
<input type="text" name="secret" value="<? echo($perm); ?>" class="hidden">
</form>
例如,这是我想在某些页面中添加的表单。在其他一些我不想要的。但是,例如,我需要根据发出调用的页面切换某些参数或更改某些值,这是我认为我无法使用 php include 完成的事情。
最佳答案
您可以使用 PHP 的 include()
函数在文件中包含 HTML。
使用您提供的 HTML 的示例
表单.php
<form action="insert.php" method="POST" class="big" style="display:none;">
<h3> Insert Contact </h3>
<fieldset class="col2">
<!-- Some inputs here -->
</fieldset>
<div>
<input type="submit" value="Send">
<input type="reset" value="Clean Form">
</div>
<input type="text" name="insert" value="1" style="display:none;">
<input type="text" name="modify" value="1" style="display:none;">
<input type="text" name="secret" value="<? echo($perm); ?>" class="hidden">
</form>
标题.php
<div>Hello World!</div>
<?php $value = 10; ?>
索引.php
<html>
<head>
</head>
<body>
<?php include(header.php); ?>
<div>This is some content. The number is <?php echo($value); ?></div>
<?php include(form.php); ?>
</body>
</html>
输出HTML
<html>
<head>
</head>
<body>
<div>Hello World!</div>
<div>This is some content. The number is 10</div>
<form action="insert.php" method="POST" class="big" style="display:none;">
<h3> Insert Contact </h3>
<fieldset class="col2">
<!-- Some inputs here -->
</fieldset>
<div>
<input type="submit" value="Send">
<input type="reset" value="Clean Form">
</div>
<input type="text" name="insert" value="1" style="display:none;">
<input type="text" name="modify" value="1" style="display:none;">
<input type="text" name="secret" value="<? echo($perm); ?>" class="hidden">
</form>
</body>
</html>
如果您想在两种不同的形式之间进行选择,可以使用以下任何一种方法:
方法一:在不同页面包含相关表单
插入.php
<?php include("insert-form.php"); ?>
编辑.php
<?php include("edit-form.php"); ?>
方法2:根据条件包含相关表单
索引.php
<?php
$formchoose = "insert";
if($formchoose == "insert") {
include("form-insert.php");
} else {
include("form-default.php");
}
?>
方法 3:在包含中执行条件(这是您在评论中询问的那个)
索引.php
<?php
$formchoose = "insert";
include(forms.php);
?>
表单.php
switch ($formchoose) {
case "insert":
?>
<form id="insert-form">
<!-- form here-->
</form>
<?
break;
case "edit":
?>
<form id="edit-form">
<!-- form here-->
</form>
<?
break;
default:
break;
}
文档
关于javascript - 如何打印 html 代码以便我只写一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454755/