我有这个html代码:
<p class="Chords">[A] [B] [C]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[D] [E] [F]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[G] [H] [I]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[J] [K] [L]</p>
<p> Some Text Goes Here </p>
我有这样的数组
["1","2","3","4","5","6","7","8","9","10","11","12"]
我要替换具有Chords类的p标签中的数组项,并且我的Content应该像这样:
<p class="Chords"> 1 2 3</p>
<p> Some Text Goes Here </p>
<p class="Chords"> 4 5 6</p>
<p> Some Text Goes Here </p>
<p class="Chords"> 7 8 9</p>
<p> Some Text Goes Here </p>
<p class="Chords"> 10 11 12</p>
<p> Some Text Goes Here </p>
答案 0 :(得分:1)
您应该这样做,首先必须提取所有需要替换的字符,然后遍历它们,并使用charCode从数组中找到每个字符的值。
const array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
const places = $("#container").html().match(/\[[A-Z]\]/g)
places.forEach(char => {
const index = char.charCodeAt(1) - 65
const template = $("#container").html();
$("#container").html(template.replace(char, array[index]))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<p class="Chords">[A] [B] [C]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[D] [E] [F]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[G] [H] [I]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[J] [K] [L]</p>
<p> Some Text Goes Here </p>
</div>
答案 1 :(得分:0)
您可以使用此正则表达式替换[value] text.replace(/\[(.*?)\]/g
$(document).ready(function() {
var arr = ["1","2","3","4","5","6","7","8","9","10","11","12"];
var text = $("#text").text();
var count = -1;
$("#text").text(text.replace(/\[(.*?)\]/g, function() {
count = count + 1;
return arr[count]
}));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='text'>
<p class="Chords">[A] [B] [C]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[D] [E] [F]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[G] [H] [I]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[J] [K] [L]</p>
<p> Some Text Goes Here </p>
</div>
答案 2 :(得分:0)
使用类p
获取所有Chords
元素,然后遍历arr以+3递增,并替换p
的textContent。
const arr = ["1","2","3","4","5","6","7","8","9","10","11","12"];
const pEles = document.querySelectorAll('.Chords');
for(let i = 0, j = 0; i < arr.length; i = i+3, j++) {
pEles[j].textContent = `${arr[i]} ${arr[i+1]} ${arr[i+2]}`;
}
<p class="Chords">[A] [B] [C]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[D] [E] [F]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[G] [H] [I]</p>
<p> Some Text Goes Here </p>
<p class="Chords">[J] [K] [L]</p>
<p> Some Text Goes Here </p>