将HTML字符串转换为Jquery对象

将HTML字符串转换为Jquery对象

本文介绍了将HTML字符串转换为Jquery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML字符串,它是文本和HTML标记的混合,我正尝试将其转换为对象.所以例如我的HTML字符串如下所示:

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:

Pay using your <img src="visa-src" /> or your <img src="mc-src" />

我正在使用jquery 1.8.0并尝试使用$(HTMLSTRING),但是由于某种原因,它在锚点之前剥离了文本并给出了其余部分,即对象的第一个文本为子级#img, #text#img (使用您的付款)被剥夺

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

但是可以说输入是否为:

However lets say if the input is:

<img src="visa-src" /> or your <img src="mc-src" />

它正确地给了我带有#img,#text和#img的三个子元素的对象.

it correctly gives me the object with three child elements in it #img, #text and #img.

还有其他方法可以正确转换吗?

Are there any other ways to convert this properly?

更新:我最终要看的是在HTML字符串中更改每个img src并在其中添加一些主机.

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.

谢谢.

推荐答案

使用

$.parseHTML()

代替

$(HTMLSTRING)

请参见下面的JS代码.

See below JS Code..

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

演示小提琴

这篇关于将HTML字符串转换为Jquery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:41