【问题标题】:Find a div with certain class and add some HTML after and before it (with PHP!)找到具有特定类的 div 并在其前后添加一些 HTML(使用 PHP!)
【发布时间】:2025-12-06 13:20:04
【问题描述】:

我有以下问题 - 如何找到一个具有“test”类的 div 并添加“</div>before 和“<div class="sth">after . 更详细的例子:

<!-- The original code -->
<div class="parent">
   ...here we can have some more content...
   <div class="test"></div>
</div>

<!-- The thing that I want to achieve -->
<div class="parent">
...here we can have some more content...
</div>

<div class="test"></div>

<div class="sth">
</div>

我尝试使用 javascript/jQuery 但没有成功,因为它是在 DOM 中生成的。 所以我决定在展示内容之前用一些可以处理的东西来做。

有什么想法可以做到吗?

(内容将由 Wordpress 帖子生成,如果对您有帮助的话……)

附言对不起我的英语不好

【问题讨论】:

  • 如果它在 DOM 中生成,那么你希望它如何在 PHP 中再次呈现?!

标签: jquery html wordpress dom wordpress-theming


【解决方案1】:

在正文标签结束之前使用您的代码,&lt;/body&gt;

jQuery(document).ready(function($) {
    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut
$( ".test" ).insertAfter( ".parent" );
});

该包装器将在 DOM 完全构建时执行您的代码。如果出于某种原因,您希望您的代码立即执行而不是等待 DOM 就绪事件,那么您可以改用这个包装方法:

    (function($) {
        // Inside of this function, $() will work as an alias for jQuery()
        // and other libraries also using $ will not be accessible under this shortcut
$( ".test" ).insertAfter( ".parent" );
    })(jQuery);

参考:http://codex.wordpress.org/Function_Reference/wp_enqueue_script

http://jsfiddle.net/itsazzad/wW4Pv/1/

【讨论】:

    【解决方案2】:

    我要做的是使用 PHP Simple HTML DOM ,获取您想要的 &lt;div&gt;,然后在之后附加其他代码。我认为这将是更简单的方法。

    【讨论】:

      【解决方案3】:

      您说您尝试使用jQuery 没有成功。但也许您想尝试这种成功的方法:

      $('.test').wrap('<div class="sth"></div>');
      

      不要忘记在 DOM 准备好时执行它:

      $(function() {
          $('.test').wrap('<div class="sth"></div>');
      });
      

      【讨论】:

        【解决方案4】:

        Javascript:

        var page = document.documentElement.InnerHTML;
        document.documentElement.InnerHTML = page.replace("<div class=\"test\">","</div><div class=\"test\"><div class=\"sth\">");
        

        【讨论】:

          【解决方案5】:

          谢谢大家。我决定将整个内容复制为纯 html 文本,而不是在加载简单的 gif 加载器时使用 jQuery 查找和替换我想要的东西。

          这不是最好和最快的解决方案,但现在就像一个魅力:-)。

          再次感谢。

          【讨论】:

          • 通过给他们投票来感谢他们,他们花费了时间和精力来帮助您。选择适合您的案例的解决方案。