无法在jQuery XML对象中插入元素 [英] Cannot insert elements in a jQuery XML object

查看:114
本文介绍了无法在jQuery XML对象中插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery 1.5中使用新的$ .parseXML()方法将字符串解析为有效的XML对象。一旦我将字符串转换为jQuery XML对象,我就能够浏览XML的DOM并查找值。我甚至可以改变不同属性的值。但是,我不能在XML中插入新元素,即使我相信这应该是可能的。以下是说明问题的代码片段:

  var myXml =< one attr ='a'><两个attr ='b'/><三attr ='c'><四attr ='d'/>< / three>< / one> 
myXml = $ .parseXML(myXml);
$(myXml).find('two')。attr('attr','new value'); //< - 这工程
alert($(myXml).find('two')。attr('attr')); //< - 这个作品也是
$(myXml).find('three')。append('< five>一些值< / 5>'); //< - 不起作用
alert($(myXml).find('five')。text())//< - null

有没有人有这方面的想法?感谢您的提前。

解决方案

这里的问题是您追加了一个字符串而不是DOM元素。要附加一个DOM元素,您需要将新XML包装在 $(...)表达式中。



<$ p $ ($'('< 5>一些值< / 5>'));

小提琴: http://jsfiddle.net/kDmD8/


I'm using the new $.parseXML() method with jQuery 1.5 to parse a string into a valid XML object. Once I convert the string to a jQuery XML object, I am able to navigate the DOM of the XML and look up values. I can even change the values of different attributes. However, I cannot insert new elements into the XML, even though I believe this is supposed to be possible. Below is a code snippet that illustrates the issue:

var myXml = "<one attr='a'><two attr='b'/><three attr='c'><four attr='d'/></three></one>";
myXml = $.parseXML(myXml);
$(myXml).find('two').attr('attr','new value'); //<-- This works
alert($(myXml).find('two').attr('attr')); //<-- This works too
$(myXml).find('three').append('<five>some value</five>'); //<-- Does not work
alert($(myXml).find('five').text()) // <--Null

Does anyone have ideas on making this work? Thanks in advance.

解决方案

The problem here is that you're appending a string instead of a DOM element. To append a DOM element you need to wrap the new XML in a $(...) expression

$(myXml).find('three').append($('<five>some value</five>'));

Fiddle: http://jsfiddle.net/kDmD8/

这篇关于无法在jQuery XML对象中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆