簡體   English   中英

首先使用<span>進行自動換行,然后使用Jquery將另一個<span>與<br> <br>分隔開來

[英]First word wrap with <span> and remaining text wrap with another <span> separated with <br> tag using Jquery

我想在一個標簽中添加第一個單詞,在另一個標簽中添加剩余文本
它們之間。 基本上我想要這種類型的html結構。

<div class="hotspot-name">
  <span>Building</span>
  <br/>
  <span>One text text</span>
</div>

無論我在下面的片段中提到了什么。

 $(".hotspot-name span").each(function () { var html = $(this).html().split(" "); html = html.slice(0, -1).join(" ") + " <br />" + html.pop(); $(this).html(html); }); 
 .hotspot-name{margin-top:10px;} 
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <div class="hotspot-name"> <span>Building One</span> </div> <div class="hotspot-name"> <span>Building Two test test</span> </div> <div class="hotspot-name"> <span>Building Three test test</span> </div> <div class="hotspot-name"> <span>Building Four</span> </div> 

謝謝!!

在一個范圍內的Array[0] ,然后剩余的值與另一個元素一起傳遞,請參閱參考數組切片到N.

我更新了顏色以區分兩個跨度

 $(".hotspot-name span").each(function () { var html = $(this).html().split(" "); html = '<span class="first_span">'+html[0] + " </span><br /><span class='second_span'>" + html.slice(1).join(" ")+'</span>'; $(this).html(html); }); 
 .hotspot-name{margin-top:10px;} .first_span{ color:green; } .second_span{ color:red; } 
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <div class="hotspot-name"> <span>Building One</span> </div> <div class="hotspot-name"> <span>Building Two test test</span> </div> <div class="hotspot-name"> <span>Building Three test test</span> </div> <div class="hotspot-name"> <span>Building Four</span> </div> 

要實現此目的,您可以將.hotspot-name元素中的span的文本拆分為數組,然后使用結果值構建兩個跨度。 試試這個:

 $('.hotspot-name span').text(function(i, t) { var arr = t.split(' '); var html = '<span>' + arr.shift() + '</span></br><span>' + arr.join(' ') + '</span>'; $(this).closest('.hotspot-name').html(html); }); 
 .hotspot-name{ margin-top: 10px; } /* only to show the effect working... */ .hotspot-name span:first-child { color: #C00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <div class="hotspot-name"> <span>Building One</span> </div> <div class="hotspot-name"> <span>Building Two test test</span> </div> <div class="hotspot-name"> <span>Building Three test test</span> </div> <div class="hotspot-name"> <span>Building Four</span> </div> 

據我所知,將是:

$(".hotspot-name span").each(function () {
  var html = $(this).html().split(" ");
  html = html.slice(1, html.length).join(" ") + " <br />" + html.pop();
  $(this).text($(this).html().split(" ")[0]+'</br>');
$(this).append(<span>'+html+'</span>');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM