[英]Find a character and insert line break
我如何使用 jQuery 查找特定字符並插入換行符?
我需要找到的字符是一個連字符 - 它總是在電子商務網站上的產品標題中,並采用以下格式:
這是標題 - 這是顏色
如何找到每個產品標題的破折號並將顏色名稱的換行符插入到單獨的行中?
我使用的確切 HTML 標記如下:
<a href="#" class="product c-3">
<div class="product-thumb">
<!-- Other code is in here / Removed for brevity -->
<div class="product-title">
This is a title - This is the colour
</div>
</div>
</a>
您可以使用replace
在元素的 HTML 中查找-
並將其替換為-<br />
。 嘗試這個:
$('.product-title').html(function(i, v) {
return v.replace('-', '-<br />');
});
如果要完全刪除連字符,可以簡單地替換為'<br />'
。
更新:現在可以通過使用箭頭函數使其更加簡潔:
$('.product-title').html((i, v) => v.replace('-', '-<br />'));
嘗試:
$('.product-title').each(function() {
var self = $(this);
self.html(self.html().replace(/-/, '-<br/>'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.