1

我目前正在做一个网站。而且我需要使用 PHP 来选择具有某个类的 div。例如:

<body>

<div class="header"></div>
<div class="other-class"></div>
<div class="one-two-three"></div>
<div class="footer"></div>

</body>

<?php
    if(div.hasClass('one-two-three'))
    {
        //function code here...
    }
?>

但请记住,我想为此使用 PHP 而不是 jQuery...

4

3 回答 3

7

如果您想操作 DOM,在将其发送到客户端之前,Dom 对象会提供您需要的东西。它甚至具有与您可能已经从 JS 知道的方法类似的方法。

$htmlString = '<html>...</html>';//either generated, or loaded from a file
$dom = new DOMDocument;
$dom->loadHTML($htmlString);//or loadHTMLFile
$divs = $dom->getElementsByTagName('div');
foreach($divs as $div)
{
    if ($div->hasAttribute('class') && strstr($div->getAttribute('class'), 'one-two-three'))
    {
        //$div ~= <div class='one-two-three'>
        $div->appendChild();//check the docs to see what you can do
    }
}

以下是您可以使用的方法的概述

于 2012-08-24T09:11:49.063 回答
0

为此使用 simplephpdom 库。您可以像在 jquery 中一样使用选择器选择表单元素。

http://simplehtmldom.sourceforge.net

于 2012-08-24T08:15:05.010 回答
0

您可能会使用 php 用内容填充 div,然后您可以先处理您的内容,然后将其打印到 div 中。如果您需要在 div 已经在浏览器中时对 div 的内容进行处理,您将需要使用 javascript 来执行此操作,或者调用 php 脚本进行处理,使用 ajax 调用后端的 php 脚本并检索响应.

于 2012-08-24T08:10:13.947 回答