【问题标题】:Applying a class to a parent element in the DOM?将类应用于 DOM 中的父元素?
【发布时间】:2011-07-22 09:50:46
【问题描述】:
        <li id="weather" class="widget-container widget-dark-blue">
            <h3 class="widget-title">Weather</h3>
            <?php include (TEMPLATEPATH . '/widgets/weather.php'); ?>
        </li>

weather.php 向天气服务发出 curl 请求并返回一个表格。通过 DomDocument 类,我读取了 td's 中的值。我将当前天气状况的类名应用于div.weather

<?php

require_once('classes/SmartDOMDocument.class.php');

$url = 'some/domain...';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);

$str = curl_exec($curl);

$dom = new SmartDOMDocument();
$dom->loadHTML($str);
$xpath = new DOMXPath($dom);

$tds = $xpath->query('//div/table/tr/td');

foreach ($tds as $key => $cell) {
    if ($key==1) {
        $condition = $cell->textContent;
        //$cell->parentNode->setAttribute('class', 'hello');
        echo "<div class='weather " . strtolower($condition) ."'>";
        ...

?>

一切正常。我唯一的问题是,是否有一种 PHP 方法可以将类名 $condition 应用于保存信息的列表项? 因此,我不想在我的 li#weather 中有一个带有 $condtion 的类,我希望有一个 li#weather 类。

&lt;li id="weather" class="widget-container widget-dark-blue $condition"&gt;

有什么方法可以将 $condition 类应用于包含所有内容的列表。我可以很容易地用 javascript/jquery 做到这一点。但是我想知道是否有一些服务器端解决方案。

谢谢

【问题讨论】:

  • 您可以使用$node-&gt;parentNode 获取节点的父节点。如果包含 &lt;li&gt; 是直接祖先,那么像 $cell-&gt;parentNode-&gt;setAttribute(...) 这样的东西可以解决问题。
  • 正如您在我上面的代码中看到的那样,它应该是直接祖先,对。两者之间没有任何东西。但是例如 $cell-&gt;parentNode-&gt;setAttribute('class', 'hello'); 不起作用。可能是因为 $cell 实际上是原始 curl-request 的 td,而不是包含此 curl-request 的列表的子级。

标签: php domdocument classname


【解决方案1】:

也许你可以试试类似的东西:

$parent = $cell->parentNode;

while ($parent->tagName != 'li')
{
    $parent = $parent->parentNode;
}

$class = $parent->getAttribute('class');
$parent->setAttribute('class', $class . ' ' . strtolower($condition));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2021-09-05
    • 2013-11-26
    • 2018-10-26
    相关资源
    最近更新 更多