How to get whole text including tags from an XML file with jQuery
I have an xml file like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<legends>
<legend>
<number>1</number>
<legendString><ul><li>1.across:a system of rules of conduct or me开发者_运维技巧thod of practice</li><li>1.down:a disagreement or argument about something important</li><li>2.down:any broad thin surface</li><li>3.across:the passage of pedestrians or vehicles </li></ul></legendString>
</legend>
......
<legends>
How can I take whole text including tags using jQuery. The string
<ul><li>1.across:a system of rules of conduct or method of practice</li><li>1.down:a disagreement or argument about something important</li><li>2.down:any broad thin surface</li><li>3.across:the passage of pedestrians or vehicles </li></ul>
should be passed if I make a function call. If I call:
var legendStr = $(this).find("legendString").text();
tags will not be present in legendStr.
How can I proceed.
This is the jQuery Script:
var randomnumber=Math.floor(Math.random()*233);
$.get("legends.xml",{},function(xml){
$(xml).find("legend").each(function(){
if(randomnumber == $(this).find("number").text())
{
var c = "legendString";
var legendStr = $(this).find(c).html();
$("#sidebar > ul").html(legendStr);
}
});
},"xml");
You want
$(this).find("legendString").html()
I took a closer look at jQuery's support for XML. .html()
doesn't support XML document. So, you'll need to either use the traversing methods and/or XML DOM.
So, For example, you could do a depth-first traversal till you find a text node (i.e. nodeType == 3), and you can use nodeName
(e.g. <ul>
) and .text() to get the tag name and the text.
Try using the .html()
method to preserve tags:
var legendStr = $(this).find('legendString').html();
Also note that .find('legendString')
will look for a tag called legendString
which probably is not what you are looking for. You probably need the :contains()
selector.
I don't think the function you need is in jQuery out-of-the-box. But you can write your own. Here is a starting point for you:
jQuery.extend(jQuery.fn, {
outerHtml: function(tagName) {
var matches = this.find(tagName);
var result = '';
for (var i=0; i<matches.length; i++) {
var el = matches[i];
result += '<' + tagName;
for (var i=0; i<el.attributes.length; i++) {
result += ' ';
result += el.attributes[i].name;
result += "='";
result += el.attributes[i].value;
result += "'";
}
if (el.innerHTML == null) { result += '/>'; }
else {
result += '>';
result += el.innerHTML;
result += '</'
result += tagName;
result += '>';
}
return result;
}
}});
thus, you'll be able to do
var legendString = $(this).outerHtml('legendString');
精彩评论