开发者

Add a Link to a xml tag and parse it with jquery

I can parse the xml with jquery. Now I want the parsed text to be a hyperlink instead of simple text. Below is what I have written.

 $(xml).find("customers")
     .each(function(){
          $("#guys").append("<div class="mybox"><a href="+$(this).find('customer_link').text()+"target="_blank">"+$(this).find('customer_company').text()"</a></div>开发者_运维百科;");                                                                                      

});

And here is the XML

    <customer_company><![CDATA[Google<br>]]></customer_company>
    <customer_link>http://www.google.com</customer_link>

</myguys>

<myguys>

    <customer_company><![CDATA[EMC<br>]]></customer_company>
    <customer_link>http://www.emc.com</customer_link>

</myguys>
</info>

I know there is nothing wrong in logic, I think this is just a syntax error with the a tag. Can somebody tell me where I am doing a mistake here and point me to a nice tutorial


You're mixing quote styles. Single quoted (') strings can contain unescaped double quotes (") and vice-versa. Having unescaped double quotes in your double-quoted string is breaking your code.

$("#guys").append("<div class="mybox"><a href="+$(this).find('customer_link')
ss^   se^       ss^         se^   ss^       se^            ss^           se^   

.text()+"target="_blank">"+$(this).find('customer_company').text()"</a></div>"); 
      ss^     se^    ss^e^            ss^              se^      ss^        se^ 

ss == string start,
se == string end 

You can see how this creates random undefined references like mybox, but doesn't build the string you intended. Try this:

$("#guys").append("<div class='mybox'><a href=" + 
    $(this).find("customer_link").text() +
    "' target='_blank'>" + 
    $(this).find("customer_company").text() + 
    "</a></div>");  

Alternatively, you can use jQuery to build all the elements and completely avoid having attributes with quotes embedded in your string:

 $("#guys").append($("<div />")
                      .addClass("mybox")
                      .append($('<a/>', {  
                          href: $(this).find("customer_link").text(),  
                          target: "_blank",  
                          text: $(this).find("customer_company").text()  
                      })));

The CDATA in your xml is going to cause jQuery problems because it is parsing the xml like it's html, not according to the xml specs. You may be better off parsing your xml with a plugin like jParse if you can't remove the CDATA and <br> from the customer_company element.


Have a look at a snippet of your code:

$("#guys").append("<div class="mybox">.......

You're closing the tags when you possibly don't mean to:

Try this:

$("#guys").append("<div class='mybox'>.......

You'll need to think a little more carefully, though, as you have some quotes in your string later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜