<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>
任何帮助?
答案 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;
}, "");
第一个例子:
$(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;
或者,如果您不想使用reduce
,这是一个无聊的旧循环:
var html = ""
a.each(function() {
html += this.outerHTML;
});
示例:
$(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;
...我能帮助但注意事项既简短又容易理解。 ; - )
答案 1 :(得分:1)