简体   繁体   English

如何使用jquery包围每个内容 <div> 用一个标签 <marquee> 标签

[英]How to use jquery to surround the contents of every <div> tag with a <marquee> tag

I am curious about how I would go about writing a one-liner to take every div and surround its contents with marquee tags using jquery. 我很好奇我将如何编写单行代码来使用每个div,并使用jquery将其内容用选取框标记包围。 For example I would like it to take 例如,我希望它采取

<div class="foo">Hello <div class="bar">World</div></div>

and turn it into 然后变成

<div class="foo"><marquee>Hello <div class="bar"><marquee>World</marquee></div></marquee></div>

My original attempt that failed: 我最初的尝试失败了:

$("div").each(function() $(this).html("<marquee>"+$(this).html()+"</marquee>")});

It failed when it reached nested div tags because the outermost tag's contents was replaced when its marquee tag was added thus invalidating references to the inner tags. 当到达嵌套的div标签时,它失败了,因为添加了字幕标签后,最外面的标签的内容被替换了,从而无效了对内部标签的引用。 I'm not super worried about executing JavaScript again . 我并不担心再次执行JavaScript。

How would you do this? 你会怎么做?

Consider the recommendations from other users about not using deprecated elements, but for exemplification purposes, the following solution: 考虑来自其他用户的关于不使用不推荐使用的元素的建议,但出于示例目的,以下解决方案:

From the jQuery docs about .html() : 从有关.html()jQuery文档中

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. 使用.html()设置元素的内容时,该元素中的所有内容都将被新内容完全替换。 Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content. 此外,在用新内容替换那些元素之前,jQuery从子元素中删除了其他构造,例如数据和事件处理程序。

The references and even events of children are removed by jQuery (well, not removed, they are just being created as new elements again, so you don't keep the previous events and references). jQuery会删除子项的引用甚至事件(嗯,不会删除,它们会再次被创建为新元素,因此您不会保留以前的事件和引用)。

Don't use .html() then, and instead create a new marquee element and append the children of the original div to it, then append that marquee to the div: 然后,不要使用.html() ,而是创建一个新的marquee元素并将原始div的子代添加到该元素,然后将该marquee附加到div:

$("div").each(function(){
    var newMarquee = $('<marquee>');
    newMarquee.append($(this).children());
    $(this).append(newMarquee);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM