jQuery技术:Jquery replaceWith不工作

使用Jquery 1.7.1

我有两个div

{page content here}

那些显示在页面源中。 但是我在页面底部添加的这个jquery不起作用:

  $(document).ready(function () { $("div.highlightStart").replaceWith("
"); $("div.highlightEnd").replaceWith("
"); });

浏览器控制台(Chrome)中没有显示javascript错误。 什么都没有被取代。

    首先,我想在网站上生成一个不正确的DOM结构。 如果您的脚本将运行,它将如下所示:

     
    {page content here}

    如果你想要的话,这不是一个好的结构:

     
    {page content here}

    应该是这样的:

    你的DOM:

     
    {page content here}

    在你的脚本中:

     $(document).ready(function () { content = $('#content').text(); $('#content').html($('
    ').text(content)); });

    请参阅我的小提琴以供参考

    replaceWith方法需要整个元素,而不是标记。 您需要使用新元素包装页面内容,然后删除两个原始div。

    更新:这可能会让你接近:

     $(document).ready(function () { $('.highlightStart').nextUntil('.highlightEnd').andSelf() .wrap('
    '); $('.highlightStart, .hightlightEnd').remove(); });

    有点不对劲,但我没时间了。 祝好运。

    根据isherwood的帮助,使用此作为解决方案:

    使用这样的HTML树:

     
    highlightStart
    Outside
    Content to Highlight
    More
    second
    third
    highlightEnd

    这个Javascript:

     $(document).ready(function () { $('.highlightStart').parent().parent().replaceWith("
    "); $('.highlightEnd').parent().parent().replaceWith("
    "); $('.highlightStart').nextUntil('.highlightEnd').andSelf().wrapAll("
    "); $('.highlightStart, .highlightEnd').remove(); });

      以上就是jQuery教程分享Jquery replaceWith不工作相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/541467.html

      (0)
      上一篇 2021年1月3日
      下一篇 2021年1月3日

      精彩推荐