<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
<span class='spanpath'>d</span>
<span class='spanpath'>e</span>
js
$('.spanpath').click(function(){
var a = html of all preceding spans + html of clicked span
});
例如,如果点击spanpath c
,则结果应为
<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
任何帮助?
答案 0 :(得分:2)
使用preveAll()
获取所有以前的项目,然后使用addBack()
将项目本身包含在对象中。
$('.spanpath').click(function(){
var a = $(this).prevAll('.spanpath').addBack();
console.log(a.clone().wrapAll('<p>').parent().html());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
<span class='spanpath'>d</span>
<span class='spanpath'>e</span>
&#13;
答案 1 :(得分:1)
试试这个:
prevAll
将获取之前的所有.spanpath
,然后您可以将其与所点击的html
.spanpath
连接起来
$('.spanpath').click(function(){
var a = $(this).html();
var b = '';
$(this).prevAll('.spanpath').each(function(){
b = $(this).html() + " " + b;
});
var a = b + " " + a;
alert(a);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
<span class='spanpath'>d</span>
<span class='spanpath'>e</span>
&#13;
答案 2 :(得分:1)
这样会更好,否则您将获得所有上传的HTML元素
$( 'spanpath')。点击(函数(){
var a = $(this).prevAll(".spanpath").andSelf();
});
答案 3 :(得分:0)
您可以使用prevAll
中的andSelf
和jQuery
方法选择所有需要的元素。然后迭代每个元素以在这些元素中获得html
内容。
$(document).ready(function() {
$('.spanpath').click(function() {
var a = "";
$(this).prevAll().andSelf().each(function() {
a += $(this).html();
});
console.log(a);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
<span class='spanpath'>d</span>
<span class='spanpath'>e</span>
注意强>
请注意andSelf
方法deprecated自jQuery
版本1.8以来,版本3.0将删除它。因此,建议改为使用addBack
方法。