使用 jQuery 将对象插入到内部 HTML 之前的其他对象中

Insert objects into other objects before the innerHTML with jQuery

本文关键字:对象 HTML 其他 内部 jQuery 插入 使用      更新时间:2023-09-26

这是我当前的工具提示:

<div class="tooltip" style="position: absolute; top: 1298px; left: 382.5px; display: none; ">this is where the tooltip text goes. You are quite the cool!</div>

忽略它有内联 CSS 一秒钟的事实(抱歉)...

好的,所以我需要在其中插入 3 个跨度 - HTML 之前为 1.5,HTML 之后为 1.5,所以最后看起来像这样:

<div class="tooltip" style="position: absolute; top: 1298px; left: 382.5px; display: none; "><span class="tooltop"></span><span class="toolmid">this is where the tooltip text goes. You are quite the cool!</span><span class="toolbot"></span></div>

但当然不知道最好的方法...

本质上它看起来像这样:

(现有div) (开始跨度/) (中间跨度) [现有内部HTML] (/中间跨度) (

结束跨度/) (/现有分形)

不知道。

您可以wrapAll现有内容,然后prepend顶部并append底部

var tooltip = $('.tooltip');                            //cache tooltip
tooltip.contents().wrapAll('<span class="toolmid" />'); //wrap existing contents
tooltip.prepend('<span class="tooltop">');              //prepend the top
tooltip.append('<span class="toolbot">');               //append the bottom

试试这个...

.HTML

<div class="tooltip" style="position: absolute; top: 1298px; left: 382.5px; display: none; ">this is where the tooltiip text goes. You are quite the cool!</div>

JavaScript

$(".tooltip").each(function(index, tooltip) {
    tooltip.innerHTML = '<span class="tooltop"></span><span class="toolmid">' + tooltip.innerHTML + '</span><span class="toolbot"></span>';
});

此代码将使用"工具提示"类查找所有元素并添加范围。

$('.existing-div-selector')
    .append(
        $('<span class="tooltop"></span><span class="toolmid">' + someContentVariable + '</span><span class="toolbot"></span>')
    );

jQuery允许你从字符串中构建DOM片段,它将从中解析和创建DOM元素。

$('<span class="tooltop"></span><span class="toolmid">' + someContentVariable + 
            '</span><span class="toolbot"></span>').
                         appendTo('your_div_selector');