【问题标题】:Why getElementById doesn't work in this case?为什么 getElementById 在这种情况下不起作用?
【发布时间】:2011-11-14 15:59:59
【问题描述】:

我有一段 PHP 代码。

PHP:

$Implementation = new DOMImplementation();
$Document = $Implementation->createDocument( NULL, NULL, $Implementation->createDocumentType( 'html' ) );
$Document->encoding = 'utf-8';
$Document->loadXML( $main_html[ 'main' ] ); // load main.html
$Document->xinclude();
$Fragment = $Document->createDocumentFragment();
$Fragment->appendXML( $main_html[ 'page' ] ); // load page.html
$Document->getElementById( 'content' )->appendChild( $Fragment );
...

除了最后一行,一切正常,出现错误:

PHP Fatal error:  Call to a member function appendChild() on a non-object

似乎getElementById() 方法不适用于$Document

查看 HTML。

HTML (main.html):

...
    </head>
    <body xmlns:xi="http://www.w3.org/2001/XInclude">
        <xi:include href="wrapper.html" />
    </body>
</html>

HTML (wrapper.html):

<section
    id="wrapper"
    xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:include href="header.html" />
    <xi:include href="nav.html" />
    <xi:include href="content.html" />
    <xi:include href="aside.html" />
    <xi:include href="footer.html" />
</section>

HTML(内容.html):

<section id="content" />

我在$Document-&gt;loadXML( $main_html[ 'main' ] ); 之前添加了$Document-&gt;validateOnParse = TRUE;,并在没有XInclude 的情况下进行了测试,但不起作用。

终于找到了解决办法,坏行替换为:

$Document->getElementsByTagName( 'section' )->item( 1 )->appendChild( $Fragment );

getElementsByTagName() 方法适用于$Document,但不能满足我。我错过了什么吗?

【问题讨论】:

    标签: php dom getelementbyid


    【解决方案1】:

    我遇到了同样的问题并得到了上述相同的答案。由于我不知道如何定义 DTD,我得到了以下解决方案:

    更改 HTML 代码:

    <section id="content" />
    

    进入

    <section xml:id="content" />
    

    如果您仍然需要显示 id 属性(出于 Javascript 目的),您可以使用以下代码:

    <section id="content" xml:id="content" />
    

    我遇到了这个解决方案的另一个问题,因为 xml:id 属性不会通过验证器。 我对这个问题的解决方案如下:保持 HTML 代码不变:

    <section id="content" />
    

    现在像这样更改您的 PHP 代码:

    /* ... Add xml:id tags */
    
    $tags = $Document -> getElementsByTagName('*');
    foreach ($tags as $tag)
      $tag->setAttribute('xml:id',$tag->getAttribute('id'));
    
    /* ... Here comes your PHP code */
    
    $Document->getElementById( 'content' )->appendChild( $Fragment );
    
    /* ... Remove xml:id tags */
    
    foreach ($tags as $tag)
      $tag->removeAttribute('xml:id');
    

    这个解决方案非常适合我。我希望你也觉得它有用:)

    【讨论】:

      【解决方案2】:

      您必须传递定义id 属性的DTD。否则不能使用getElementById

      有关详细信息,请参阅:

      【讨论】:

        猜你喜欢
        • 2017-11-26
        • 2010-12-29
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多