2017-04-20 55 views
-1

我正在用這段代碼創建一個元素。設置它應該設置的ID。 (我需要的validateonparse?):getelementbyid動態創建的元素不能正常工作

$sectionContainer = $dom->createElement('div', $section); 
$sectionContainer->setAttribute("id", $section); 
$sectionContainer->setIdAttribute("id", TRUE); 
$dom->validateOnParse = true; 
$divup->parentNode->insertBefore($sectionContainer, $divup); 


echo 'avant'."</br>"; 
echo $section; 
print_r($dom->getElementById($section)->getAttribute('id')); 
echo 'apres'."</br>"; 

但我得到這個: 致命錯誤:未捕獲的錯誤:調用一個成員函數的getAttribute()上的空

所以它無法找到元素我剛創建,爲什麼?

回答

0

Hey_那裏,

的問題不在於$dom->validateOnParse = true;

您的錯誤來自此行 - $sectionContainer->setIdAttribute("id", TRUE);

如果你想設置DOMElement的id屬性,就像<div id="myId"></div>你只需要你已經有的$domElement->setAttribute("id", "myId");

DOMElement::setIdAttribute實際上是表明該屬性是唯一的標識符,無關與id="myId"屬性

(PHP 5, PHP 7)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

Description

public void DOMElement::setIdAttribute (string $name , bool $isId)

Declares the attribute name to be of type ID.

那麼它是不是很清楚什麼是類型ID,但我可以說,這是與html元素的id屬性不同。

檢查演示HERE

+0

在您的例子,什麼是之前和之後輸出停留? Before和After之間只有一個輸出。所以它很混亂。 – Meglio

+0

我也不知道。我發現這個平臺上的代碼可以被覆蓋,我想有人編輯它......這個主題的重要之處在於,如果你想設置'id'屬性,你可以使用[** setAttribute **](http ://php.net/manual/en/domelement.setattribute.php)而不是[** setIdAttribute **](http://php.net/manual/en/domelement.setidattribute.php) – codtex

+0

我認爲代碼之前和之後只會混淆事物。 – Meglio