我希望在列表中添加注释。有人可以帮帮我吗?
<dl class="listings">
<dt>Apple</dt>
<dd>Delicious</dd>
<dt>Green Apple</dt>
<dd>Love it!</dd>
</dl>
<table>
<tr>
<td>Apple, Orange, Banana</td>
<td>Green Apple, Lemon</td>
</tr>
</table>
$(document).ready(function () {
$(".listings").find('dt').each(function() {
var title = $(this).html();
var comment = $(this).next().html();
$('table td').filter(":contains('"+title+"')").each(function(){
$(this).html('<span>'+title+'</span><span>'+comment+'</span>');
});
});
});
预期
Apple Delicious, Orange, Banana
Green Apple Love it!, Lemon
结果
Apple Delicious
Apple Delicious
答案 0 :(得分:1)
以下假定您要更改的表格中的短语/单词均以逗号分隔。
否则“Apple”本身也会在“Green Apple”中找到,并且可以变成“Green Apple Delicious Love it”之类的东西。
因此必须拆分所有短语,并分别对每个短语进行直接的等式匹配
$(".listings").find('dt').each(function() {
var title = $(this).html();
var comment = $(this).next().html();
$('table td').filter(":contains('" + title + "')").html(function(_, currHtml) {
// break all the phrases into array by splitting at comma
// and map array to new html strings
return currHtml.split(',').map(function(phrase){
// check each phrase/word separately
phrase = phrase.trim()
if(phrase===title){
return '<span>' + title + '</span><span> ' + comment + '</span>'
}else{
return phrase;
}
// join array back into string
}).join(', ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="listings">
<dt>Apple</dt>
<dd>Delicious</dd>
<dt>Green Apple</dt>
<dd>Love it!</dd>
</dl>
<table>
<tr>
<td>Apple, Orange, Banana</td>
</tr>
<tr>
<td>Green Apple, Lemon</td>
</tr>
</table>
答案 1 :(得分:0)
以下是我对此的看法 - 您可以使用split
将逗号分隔每个<td>
字作为分隔符。
然后使用indexOf
查看数组,看看你的标题和td字是否匹配
如果是这样,那么添加你的html并按照join(",")
$(document).ready(function() {
$(".listings").find('dt').each(function() {
var title = $(this).html();
var comment = $(this).next().html();
$('table td').each(function() {
// split the td text into an array using , a the deliminator
var split = $(this).text().trim().split(",");
// indexOf will let us know if the title is in this array
var index = split.indexOf(title);
// if its in the array then add the comment
if (index > -1) {
// we have a match in this <td>
split[index] = '<span>' + title + '</span> <span>' + comment + '</span>'
// put the array back to the way it was with a ,
$(this).html(split.join(", "));
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="listings">
<dt>Apple</dt>
<dd>Delicious</dd>
<dt>Green Apple</dt>
<dd>Love it!</dd>
</dl>
<table>
<tr>
<td>Apple, Orange, Banana</td>
</tr>
<tr>
<td>Green Apple, Lemon</td>
</tr>
</table>