将 HTML 字符串转换为 Jquery 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19443345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert HTML string into Jquery Object
提问by user320550
I have a HTML string which is a mix of text plus HTML tags, which i'm trying to convert into an object. So for e.g. my HTML string would look like:
我有一个 HTML 字符串,它混合了文本和 HTML 标签,我正试图将其转换为一个对象。所以例如我的 HTML 字符串看起来像:
Pay using your <img src="visa-src" /> or your <img src="mc-src" />
I'm using jquery 1.8.0 and tried using $(HTMLSTRING)
however for some reason it strips out the text before the anchor and gives the rest, i.e. object with the children #img, #text
and #img
while the first text (Pay using your) gets stripped off
我使用jQuery 1.8.0,并尝试使用$(HTMLSTRING)
但是由于某种原因,它剔除了锚之前的文本,并给出了休息,即对象与孩子们#img, #text
和#img
在第一文本(使用你的工资)被剥去
However lets say if the input is:
但是,如果输入是:
<img src="visa-src" /> or your <img src="mc-src" />
it correctly gives me the object with three child elements in it #img, #text and #img.
它正确地给了我包含三个子元素的对象#img、#text 和#img。
Are there any other ways to convert this properly?
还有其他方法可以正确转换吗?
Update: What i'm ultimately looking at is to change the each of the img src there in the HTML string and prepend with some host there.
更新:我最终要考虑的是更改 HTML 字符串中的每个 img src 并在那里添加一些主机。
Thanks.
谢谢。
采纳答案by nik
Use
用
$.parseHTML()
instead of
代替
$(HTMLSTRING)
See below JS Code..
见下面的JS代码..
var HTMLSTRING = 'Pay using your <img src="visa-src" /> or your <img src="mc-src" />';
var HTMLSTRING1 = '<img src="visa-src" /> or your <img src="mc-src" />';
console.log($.parseHTML(HTMLSTRING));
console.log($.parseHTML(HTMLSTRING1));
回答by Renan Araújo
$.parseHTML()
parses a string into an array of DOM nodes.
$.parseHTML()
将字符串解析为 DOM 节点数组。
To create the objectyou need to add $()
:
要创建您需要添加的对象$()
:
$($.parseHTML(yourString))
Take a look at this fiddle: http://jsfiddle.net/j05ucnfv/
看看这个小提琴:http: //jsfiddle.net/j05ucnfv/
Reference: http://api.jquery.com/jQuery.parseHTML/