-1

Output of some elements is not working.

When I now start the website, it should get the XML from text area box and only list some elements.

Here is the script:

<script>
$(document).ready(function() {
    // Get text from textarea
    var myxml = $("#xml").val();
    $(myxml).find("resources").each(function() {
    var car = $(this).find("car").text();
    var car2 = $(this).find("car2").text();
    var out = car+"</br>"+car2;
    $("#output").append(out);
    });
});
</script>

Here is the body:

<p id="output"></p>
<!--textarea with the xml structure-->
<textarea rows="4" cols="50" id="xml">
    <resources>
    <string name="car">Ford</string>
    <string name="car2">Audi</string>    
    </resources>
</textarea> 

I don't know, where the mistake is.

4

2 回答 2

1

试试这个演示http://jsfiddle.net/devmgs/aV2x4/

$(document).ready(function() {

// Get text from textarea
//var myxml = $("#xml").val();
   var myxml = $.parseXML( $("#xml").val() );
$xml = $( myxml )
//$(myxml).find("resources").each(function() {

//var car = $(this).find("[name='car']").text();
//var car2 = $(this).find("[name='car2']").text();
//var out = car+"</br>"+car2;
var car =($xml.find( "string[name='car']" ).text());
var car2 =($xml.find( "string[name='car2']" ).text());
    var out = car+"</br>"+car2;
$("#output").append(out);

//});
});

您必须先将 xml 转换为 jquery xml 对象

于 2013-09-30T12:01:23.887 回答
0

你正在尝试$(myxml).find("resources")一个字符串(在这个阶段myxml是一个字符串)。看http://api.jquery.com/jQuery.parseXML/

<script type="text/javascript">
jQuery(document).ready(function()
{


    // Get text from textarea
    var myxml = jQuery("#xml").val();
    //console.log(myxml);

var xmlDoc = jQuery.parseXML( myxml );

    jQuery(xmlDoc).find("resources").each(function() {
    //console.log(this);
    var car = jQuery(this).find("car").text();
    var car2 = jQuery(this).find("car2").text();
    var out = car+"</br>"+car2;


    jQuery("#output").append(out);


    });

}); // ready
</script>
于 2013-09-30T12:00:43.953 回答