我有一个这样的菜单列表:
<ul>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
</ul>
如何从li.but自动选择第二个单词并将其变成这样的跨度:
<ul>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
</ul>
非常感谢!
答案 0 :(得分:7)
你走了:
$('li.but > a').html(function(i, v) {
return v.replace(/\s(.*?)\s/, ' <span>$1</span> ');
});
答案 1 :(得分:3)
这样的事情:
$('ul > li.but > a').html(function (i, oldHtml)
{
return oldHtml.replace(/(\s)(\w+)/, '$1<span>$2</span>');
});
答案 2 :(得分:1)
下面:
$('.but a').each(function() {
var $a = $(this);
var $small = $a.find('small');
var smallText = $small.html();
$small.remove();
var arr = $a.html().split(' ');
arr[1] = ['<span>', arr[1], '</span>'].join('');
$a.html(arr.join(' ')).append(['<small>', smallText, '</small>'].join(''));
});
答案 3 :(得分:1)
你去吧
$("ul > li > a").each(function(index, el) {
var sec = $(this).html().split(" ");
sec = sec[1].split("<")[0];
var total = "<span>" + sec + "</span>";
var html = $("ul > li > a").html();
html = html.replace(sec, total);
$(this).html(html);
});
答案 4 :(得分:1)
下面是一个用类包装第二个单词的代码。也许你可以采用它。做这样的事情;
$('.list-item a').each(function(){
var text = $(this).text().split(' ');
if(text.length < 2)
return;
text[1] = '<span class="color-red">'+text[1]+'</span>';
$(this).html( text.join(' ') );
});