我想在一个标签中添加第一个单词,在另一个标签中添加剩余文本,它们之间用
分隔。基本上我想要这种类型的 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]
在一个范围内,然后剩余的值与另一个元素一起传递,请参阅引用资料 Array slice upto N .
我更新了 color 以区分两个跨度
$(".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>
关于javascript - 第一个单词用 <span> 换行,其余文本用另一个 <span> 换行,使用 Jquery 用 <br> 标记分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023319/