我試圖通過PHP的DOM文檔通過HTML塊重構內嵌<img>
元素:http://www.appelsiini.net/projects/lazyload無法追加第二個元素與PHP的DOMDocument
對於每個<img>
我試圖插入一個重構重複,然後將原始文件包裝爲<noscript>
標籤以獲取非JS後備。
實施例:
輸入:
<img src="img/example.jpg" width="640" heigh="480">
輸出:
<img class="lazy" src="img/grey.gif" data-original="img/example.jpg" width="640" heigh="480"><noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>
我有包裹工作和新的元件還構建正確。問題是,第二個appendChild
(下)不起作用,我不明白爲什麼。誰能提供解決方案?
我有以下代碼:
$noScript = $dom->createElement('noscript');
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src = $image->getAttribute('src');
$alt = $image->getAttribute('alt');
$title = $image->getAttribute('title');
$style = $image->getAttribute('style');
$newImage = $dom->createElement('img');
$newImage->setAttribute('class', 'lazy');
$newImage->setAttribute('data-original', $src);
$newImage->setAttribute('src', '/images/whitespace.gif');
if ($style) $newImage->setAttribute('style', $style);
if ($alt) $newImage->setAttribute('alt', $alt);
if ($title) $newImage->setAttribute('title', $title);
$noScriptClone = $noScript->cloneNode();
$image->parentNode->replaceChild($noScriptClone, $image);
$noScriptClone->appendChild($image);
$noScriptClone->parentNode->appendChild($newImage);
}
return $dom->saveHTMLExact();