2012-04-19 140 views
0

所以我有一個快速爲你 - 它看起來很簡單的......對象插入的innerHTML之前的其他對象使用jQuery

這裏是我目前的工具提示:

<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> 

忽視的事實它有內聯CSS爲秒(對不起)...

好了,所以我需要插入3個跨到它 - 1.5前1.5 HTML之後,所以它看起來像這到底:

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

,但當然不知道要做到這一點的最好辦法...

本質上,它是這樣的:

(現有的div)(開始跨度/)(中跨度)現有innerHTML](/中間跨度)(結束跨度/)(/現有div)

不知道。

+0

你是什麼意思,-1.5之前和1.5之後? – wkm 2012-04-19 04:35:06

+0

對不起,這令人困惑......我需要將現有div(tooltip)的innerHTML加入以下內容:&後面的內容:< span class =「toolbot」> – 2012-04-19 04:36:22

+0

如何插入''的一半? – 2012-04-19 04:40:40

回答

3

您可以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 
+0

唯一不錯的jQuery答案迄今爲止 – 2012-04-19 05:01:08

+0

輝煌。令人印象深刻:D – 2012-04-20 00:40:27

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

jQuery允許您從字符串中構建DOM片段,它將解析並創建DOM元素。

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

嘗試......

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>'; 
}); 

此代碼將找到所有與「tooltip」類的元素並添加到跨度。

+1

輝煌 - 你贏了:D – 2012-04-19 04:45:46

相關問題