我认为这是一个非常棒的问题,但我现在已经考虑了很多个小时了,而我却无法弄明白。
我需要在下面使用此HTML代码并获取.project_name span& .location跨度合并到同一个范围。
<ol id="projects" class="wide">
<li class="dontsplit" id="1234">
<a href="/projects/1234" class="thickbox dontsplit">
<span class='project_name dontsplit'>First Project Name</span>
<span class='location dontsplit'>Combined with First Location</span>
<span class='extra-info-span1'></span>
</a>
</li>
<li class="dontsplit" id="1233">
<a href="/projects/1233" class="thickbox dontsplit">
<span class='project_name dontsplit'>Second Project Name</span>
<span class='location dontsplit'>Combined with Second Location</span>
<span class='extra-info-span2'></span>
</a>
</li>
<li class="dontsplit" id="1232">
<a href="/projects/1232" class="thickbox dontsplit">
<span class='project_name dontsplit'>Third Project Name</span>
<span class='location dontsplit'>Combined with Third Location</span>
<span class='extra-info-span3'></span>
</a>
</li>
</ol>
我有这个jQuery代码,可以在第一组spans中正确执行,但会继续使用第一个span的内容来填充其余的内容。
var s1 = $('.project_name').html();
$('.project_name').remove();
$('.location').prepend(s1 + ' ');
我假设我需要使用.each()或类似的东西,但我无法找出正确的语法来使其工作。这是我a jsFiddle到目前为止所拥有的。
有什么想法吗?这可能很简单。
答案 0 :(得分:2)
如果您想保留<span>
代码...(fiddle)
$(".location").each(function() {
$(this).prepend(" ").prepend($(this).prev());
});
在这里,如果您不想要保留<span>
代码...(fiddle)
$(".location").each(function() {
$(this).prepend($(this).prev().text() + " ");
$(this).prev().remove();
});
这当然可以通过循环.project_name
跨度来完成,我只是喜欢用.location
进行,因为这是我们实际保留的内容。
执行$("selector").each(function() { });
时,您可以使用$(this)
来访问当前正在迭代的对象。
答案 1 :(得分:0)
如果你想使用你的代码:
$('.dontsplit').each (function () {
var html = $('.project_name', this).html();
$('.project_name', this).remove();
$('.location', this).prepend(s1 + ' ');
});
如果不是,我更喜欢这个代码(它更像 clear 发生了什么,我认为可读性很重要):
$('.dontsplit').each (function () {
var text_1 = $('.project_name', this).text();
var text_2 = $('.locaton', this).text();
$('.project_name', this).remove()
$('.locaton', this).remove();
var text = text_1 + text_2
$('<span></span>').text(text_1 + text_2).appendTo(this);
});
答案 2 :(得分:0)
这应该有效
var spantext="";
spantext += $('.project_name').text() + ", " + $('.location').text();
$('.project_name').remove();
$('.location').text(spantext);
答案 3 :(得分:0)
试试这个:
$('.project_name').each(function(el){
var s1 = el.html();
el.remove();
$(el.parent(),'.location').prepend(s1 + ' ');
})