[英]Jquery replaceWith not working
Using Jquery 1.7.1 使用Jquery 1.7.1
I have two divs 我有两个div
<div class="highlightStart"></div>
{page content here}
<div class="highlightEnd"></div>
Those show up in the page source. 那些显示在页面源中。 But this jquery I added at the bottom of the page is not working: 但是我在页面底部添加的这个jquery不起作用:
<script type="text/javascript" id="makeHighlight">
$(document).ready(function () {
$("div.highlightStart").replaceWith("<section class='highlight'>");
$("div.highlightEnd").replaceWith("</section>");
});
</script>
No javascript errors showing in the browser console (Chrome). 浏览器控制台(Chrome)中没有显示javascript错误。 Just nothing gets replaced. 什么都没有被取代。
First i want to site that you're a producing an incorrect structure of DOM. 首先,我想站点,你是一个产生不正确的DOM结构。 If your script will run it will looks like this: 如果您的脚本将运行,它将如下所示:
<div class="highlightStart"><section></div>
{page content here}
<div class="highlightEnd"></section></div>
and this is not a good structure if you want have: 如果你想要的话,这不是一个好的结构:
<section>
{page content here}
</section>
Should be something like this: 应该是这样的:
Your DOM: 你的DOM:
<div id="content">
{page content here}
</div>
And in your script: 在你的脚本中:
$(document).ready(function () {
content = $('#content').text();
$('#content').html($('<section>').text(content));
});
The replaceWith method expects entire elements, not tags. replaceWith方法需要整个元素,而不是标记。 You'll need to wrap your page contents with a new element, then remove the two original divs. 您需要使用新元素包装页面内容,然后删除两个原始div。
Update: This might get you close: 更新:这可能会让你接近:
$(document).ready(function () {
$('.highlightStart').nextUntil('.highlightEnd').andSelf()
.wrap('<section class="highlight"></section>');
$('.highlightStart, .hightlightEnd').remove();
});
http://jsfiddle.net/isherwood/H36UE http://jsfiddle.net/isherwood/H36UE
Something's off a bit with this, but I'm out of time. 有点不对劲,但我没时间了。 Good luck. 祝好运。
Based on help from isherwood, used this as the solution: 根据isherwood的帮助,使用此作为解决方案:
http://jsfiddle.net/H36UE/1/ http://jsfiddle.net/H36UE/1/
With HTML tree like this: 使用这样的HTML树:
<div><div><div class="highlightStart">highlightStart</div></div></div>
<div>Outside<div>Content to Highlight</div>More</div>
<div>second</div>
<div>third</div>
<div><div><div class="highlightEnd">highlightEnd</div></div></div>
This Javascript: 这个Javascript:
$(document).ready(function () {
$('.highlightStart').parent().parent().replaceWith("<div class='highlightStart'>");
$('.highlightEnd').parent().parent().replaceWith("<div class='highlightEnd'>");
$('.highlightStart').nextUntil('.highlightEnd').andSelf().wrapAll("<section class='highlight'>");
$('.highlightStart, .highlightEnd').remove();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.