简体   繁体   English

去掉 <div> 使用PHP的innerHTML

[英]Remove <div> innerHTML with php

I try to change a html page through php. 我尝试通过php更改html页面。 The idea is to reinvent the "contenteditable" attribute and change text on the fly. 想法是重新发明“ contenteditable”属性并即时更改文本。 But I want to save it in the original html. 但我想将其保存在原始html中。 For this I have some initial text in a div element. 为此,我在div元素中有一些初始文本。 This I convert to a form with a textarea, reload the page and then I can play with the text. 我将其转换为带有文本区域的表单,重新加载页面,然后可以播放文本。 Next I want to return the content of the textarea into the original div. 接下来,我想将textarea的内容返回到原始div中。 It should replace the old text. 它应该替换旧文本。 It seems to work, except that the old text is always appended and I cannot get rid of it. 似乎总是可行,但总是会附加旧文本,而我无法摆脱它。 The problem is probably in the setInnerHTML function. 问题可能出在setInnerHTML函数中。 I tried: 我试过了:

$element->parentNode->removeChild($element);

but it did not work for some reason. 但是由于某种原因它没有起作用。 Thanks! 谢谢!

<?php
$text = $_POST["text"];
$id = $_GET["id"];
$ref = $_GET["ref"];
$html = new DOMDocument(); 
$html->loadHTMLFile($ref.".html"); 
$html->preserveWhiteSpace = false;
$html->formatOutput       = true;
$elem = $html->getElementById($id); 

function setInnerHTML($DOM, $element, $innerHTML) 
  {
  $DOM->deleteTextNode($innerHTML);  
  $element->parentNode->removeChild($element);
  $node = $DOM->createTextNode($innerHTML);  
  $element->appendChild($node);
  }
setInnerHTML($html, $elem, $text);


$html->saveHTMLFile($ref.".html");
?>

Try changing your setInnerHTML to look like this: 尝试将setInnerHTML更改为以下形式:

function setInnerHTML($DOM, $element, $innerHTML) {
  $node = $DOM->createTextNode($innerHTML);
  $children = $element->childNodes;
  foreach ($children as $child) {
    $element->removeChild($child);
  }
  $element->appendChild($node);
}

Tell me if it is the result you desired. 告诉我这是否是您想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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