关于javascript:jQuery replaceWith不起作用

Jquery replaceWith not working

使用Jquery 1.7.1

我有两个股利

1
{page content here}

那些出现在页面源中。但是我在页面底部添加的这个jQuery无法正常工作:

1
2
3
4
5
<script type="text/javascript" id="makeHighlight">
   $(document).ready(function () {
     $("div.highlightStart").replaceWith("<section class='highlight'>");
     $("div.highlightEnd").replaceWith("</section>");
   });

浏览器控制台(Chrome)中没有显示JavaScript错误。只是什么都没有被替换。


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

1
2
3
<section>
{page content here}
</section>

这不是一个好的结构,如果您想拥有:

1
2
3
<section>
{page content here}
</section>

应该是这样的:

您的DOM:

1
{page content here}

在您的脚本中:

1
2
3
4
5
$(document).ready(function () {
  content = $('#content').text();

  $('#content').html($('<section>').text(content));
});

请参阅myfiddle以获取参考


基于isherwood的帮助,将其用作解决方案:

http://jsfiddle.net/H36UE/1/

使用这样的HTML树:

1
2
3
4
5
highlightStart
OutsideContent to HighlightMore
second
third
highlightEnd

此Javascript:

1
2
3
4
5
6
7
$(document).ready(function () {
  $('.highlightStart').parent().parent().replaceWith("");
  $('.highlightEnd').parent().parent().replaceWith("");
  $('.highlightStart').nextUntil('.highlightEnd').andSelf().wrapAll("<section class='highlight'>");

 $('.highlightStart, .highlightEnd').remove();
});

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

更新:这可能使您接近:

1
2
3
4
5
6
$(document).ready(function () {
   $('.highlightStart').nextUntil('.highlightEnd').andSelf()
       .wrap('<section class="highlight"></section>');

    $('.highlightStart, .hightlightEnd').remove();
});

http://jsfiddle.net/isherwood/H36UE

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