如何获取前面元素的html

时间:2016-08-05 05:55:36

标签: jquery html

<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>

任何帮助?

4 个答案:

答案 0 :(得分:2)

使用preveAll()获取所有以前的项目,然后使用addBack()将项目本身包含在对象中。

&#13;
&#13;
$('.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;
&#13;
&#13;

答案 1 :(得分:1)

试试这个:

prevAll将获取之前的所有.spanpath,然后您可以将其与所点击的html

.spanpath连接起来

&#13;
&#13;
$('.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;
&#13;
&#13;

答案 2 :(得分:1)

这样会更好,否则您将获得所有上传的HTML元素

$( 'spanpath')。点击(函数(){

var a = $(this).prevAll(".spanpath").andSelf();

});

答案 3 :(得分:0)

您可以使用prevAll中的andSelfjQuery方法选择所有需要的元素。然后迭代每个元素以在这些元素中获得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方法deprecatedjQuery版本1.8以来,版本3.0将删除它。因此,建议改为使用addBack方法。