Getting HTML from XML with JavaScript/jQuery

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 09:18:44

问题


I've got an XML document that contains a tag that has well-formed HTML content. I need to get that HTML into my page using JavaScript. However, due to CMS issues, the HTML CANNOT be escaped with < ![CDATA[ ]]> or anything else, and the <> must be present, not encoded to &lt ; &gt ;

<submenu>
    <content>
        <div>
            <h3>Hello World</h3>
            <p>Lorem <a href="ipsum.html">ipsum</a></p>
        </div>
    </content>
</submenu>

I've used jQuery to get the XML and put the submenu's into an array. I'm able to get the text with:

$(menuArray[n]).find('content').text();

However, this just returns "Hello World Lorem ipsum". I need the HTML. Unfortunately jQuerys' .html() method doesn't work with XML.

Is there any other way? Thanks in advance.


回答1:


Not overly clean but could you not use something like found in this example JQuery Object to Sring and do something like... var myHTML = $('<div>').append($(menuArray[n]).find('content').clone()).remove().html();

Ugly I know but should work




回答2:


@Sam Nicholson gave us a good idea. I used it for a while, but now i solved my problem through another way.

By setting AJAX property 'dataType' to 'html' and forcing the server response to be text/html rather than text/xml. jQuery will let you use .html() to manipulate the nodes of your XML tree sent from your server



来源:https://stackoverflow.com/questions/4980786/getting-html-from-xml-with-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!