如何将html字符串拆分为DOM元素? [英] How to split html string to DOM elements?

查看:123
本文介绍了如何将html字符串拆分为DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html字符串

I have a html string

var str = '<span class="linq" onclick="ShowData(2,-1,1);">11111</span> &nbsp;»&nbsp; <span class="linq" onclick="ShowData(16,1,1);">22222</span> &nbsp;»&nbsp; 33333';

我需要将其拆分为数组。

I need to split it to an array.

arr[0] = "<span class="linq" onclick="ShowData(2,-1,1);">11111</span>";
arr[1] = "&nbsp;»&nbsp;"
arr[2] = "<span class="linq" onclick="ShowData(16,1,1);">22222</span>";
arr[3] = "&nbsp;»&nbsp; 33333'"

我尝试使用$ .parseHTML(),但我使用的是jquery 1.6,现在无法升级。
如果我使用$(str)我得到一个数组但没有最后一项。

I tried to use $.parseHTML() but i'm using jquery 1.6 and can't upgrade for now. If i use $(str) i get an array but without the last item.

arr[0] = "<span class="linq" onclick="ShowData(2,-1,1);">11111</span>";
arr[1] = "&nbsp;»&nbsp;"
arr[2] = "<span class="linq" onclick="ShowData(16,1,1);">22222</span>";


推荐答案

这是一种方法:

var temp = document.createElement('div');
temp.innerHTML = str;

var arr = Array.prototype.map.call(temp.childNodes, function(node) {
    return node.nodeType === 1 
         ? node.outerHTML
         : node.nodeValue;
});

这篇关于如何将html字符串拆分为DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆