在PHP中包含模板时删除旧内容

时间:2018-03-29 07:44:28

标签: javascript php jquery

<?php include "main.php" #this file is supposed to be included after an event occurred ?>

 <!-- this should be deleted after include, also styles scripts and everything in this old-content id-->
         <div id="old-content">
         <link rel="stylesheet" href="custom.css">
    some content
        </div>

我尝试了,我在旧内容div中添加了以下内容,但jquery仅包含在模板中main.php

$("#old-content").empty();
  

问题在于,文件实际上并未删除,当我查看页面源时,我可以看到最后的旧内容

4 个答案:

答案 0 :(得分:1)

您可以使用.remove()方法从DOM中获取元素。当你想要删除元素本身及其中的所有内容时使用它。

$("#old-content").remove();

// find elements
var button = $("button")

// handle click and add class
button.on("click", function(){
  $("#banner-message").remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button>Remove</button>
</div>

答案 1 :(得分:0)

尝试删除()

$("#old-content").remove();

答案 2 :(得分:0)

这是我如何做到的:

<?php if (file_exists('main.php')) : ?>
    <?php include 'main.php'; ?>

    <script>
        jQuery(document).ready(function($)
        {
            $('#old-content').remove()
        })
    </script>
<?php endif; ?>

关于这一点的好处是,如果文件不存在,那么软包含警告会被拾取并且代码不会运行,而只是将代码放在条件之外将始终运行该函数并删除内容,即使未成功包含

答案 3 :(得分:0)

我认为jquery之间存在冲突。所以使用这样的javascript代码。

var x = document.getElementById("old-content"); 

x.remove(x.selectedIndex);