prevAll - 如何获取HTML而不是对象?

时间:2016-08-07 10:57:20

标签: jquery console local-storage

<span class='spant'>sky</span>
<span class='spant'>sea</span>
<span class='spant'>earth</span>
<span class='spant'>moon</span>

JS

$(document).on('click', '.spant', function () {
    var a = $(this).prevAll('.spant').addBack();
    console.log(a);
    localStorage.setItem('path', a);
});
例如,

点击范围earth 控制台结果:

[span.spant, prevObject: m.fn.init[0], context: span.spant]

localStorage结果:

[object Object]

我需要的是(console和localStorage):

<span class='spant'>sky</span><span class='spant'>sea</span><span class='spant'>earth</span>

任何帮助?

2 个答案:

答案 0 :(得分:2)

您可以使用Array#reduce创建匹配元素的outerHTML字符串,使用get从jQuery对象中获取真正的数组:

var html = a.get().reduce(function(html, element) {
  return html + element.outerHTML;
}, "");

...或者在 jQuery对象上使用reduce

var html = Array.prototype.reduce.call(a, function(html, element) {
  return html + element.outerHTML;
}, "");

第一个例子:

&#13;
&#13;
$(document).on('click', '.spant', function () {
    var a = $(this).prevAll('.spant').addBack();
    var html = a.get().reduce(function(html, element) {
      return html + element.outerHTML;
    }, "");
    console.log(html);
    //localStorage.setItem('path', html);
});
&#13;
<span class='spant'>sky</span>
<span class='spant'>sea</span>
<span class='spant'>earth</span>
<span class='spant'>moon</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

或者,如果您不想使用reduce,这是一个无聊的旧循环:

var html = ""
a.each(function() {
  html += this.outerHTML;
});

示例:

&#13;
&#13;
$(document).on('click', '.spant', function () {
    var a = $(this).prevAll('.spant').addBack();
    var html = ""
    a.each(function() {
      html += this.outerHTML;
    });
    console.log(html);
    //localStorage.setItem('path', html);
});
&#13;
<span class='spant'>sky</span>
<span class='spant'>sea</span>
<span class='spant'>earth</span>
<span class='spant'>moon</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

...我能帮助但注意事项既简短又容易理解。 ; - )

答案 1 :(得分:1)

这似乎对我有用:

ID

选中 https://fiddle.jshell.net/sjdxofxj/