我需要编写一段代码,用 br 分割 html,找到以数字开头的行,然后添加 span 标签。
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^[0-9]+[^)]/;
var lines = $('.caption').html().split(brExp).filter(line => swn.test(line.trim()));;
jQuery.each(lines, function() {
console.log(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="caption">
BBQ Porked Rolls.
Ingredients:
3 to 4 pounds pork shoulder<br />
1 tablespoon salt<br />
2 tablespoons brown sugar<br />
STEPS:
In the oven,...
<div>
我已经得到了这些行,剩下的就是在这些行周围添加 span 标签,而不需要为结果创建一个新的 div。也许通过使用 replace()
、wrap()
或完全其他的东西。这就是我需要帮助的地方。
预期输出:
<span itemprop="recipeIngredient">3 to 4 pounds pork shoulder</span><br>
<span itemprop="recipeIngredient">1 tablespoon salt</span><br>
<span itemprop="recipeIngredient">2 tablespoons brown sugar</span><br>
谢谢
最佳答案
您只需要map()超过集合。
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp).map(function (line) {
// strip the whitespace
line = line.trim();
// check for number
if ( swn.test(line) ) {
// add enclosing span
line = '<span itemprop="recipeIngredient">' + line + '</span>';
}
// return the line for the new collection
return line;
}).join('<br />');
$('.caption').html(lines);
});
如果您只想更改第一行,可以对代码进行以下细微更改:
jQuery(document).ready(function($) {
var firstOnly = true; // will check for number when this value is true
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp).map(function (line) {
// strip the whitespace
line = line.trim();
// check 'firstOnly' is true before checking for number
if ( firstOnly && swn.test(line) ) {
// add enclosing span
line = '<span itemprop="recipeIngredient">' + line + '</span>';
// first matching line has been modified
// so set 'firstOnly' to false
firstOnly = false;
}
// return the line for the new collection
return line;
}).join('<br />');
$('.caption').html(lines);
});
关于javascript - 在元素中查找行,然后用 <span> 标签将其包裹起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50214465/