将HTML字符串转换为Jquery对象

[英]Convert HTML string into Jquery Object


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.

2 个解决方案

#1


11  

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

Demo Fiddle

#2


24  

$.parseHTML() parses a string into an array of DOM nodes.

$ .parseHTML()将字符串解析为DOM节点数组。

To create the object you 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/


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/10/18/3a686d41c9ffefbef2a3208fd1fe32fa.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号