jquery嵌套了每个问题
请参见下方编辑。 我试图让一些jquery在我正在构建的wordpress插件中工作。 (在wordpress,fyi中使用jquery时,使用字符串’jQuery’代替’$’成语)
示例xml:
Some Name 一个地址 09年1月1日
示例jquery:
jQuery(text).find("person").each(function(){ jQuery("#active_list") .append( "" + jQuery(this).find("Name").text() + " at " ; jQuery(this) .find("location") .each(function(){ jQuery("#active_list") .append( jQuery(this).find("locationName").text() + " on " ) ; }) ; jQuery("#active_list") .append( jQuery(this).find("date").find("startDate").text() + "" ) ; });
然后产生了坏标记:
某些名称位于一个地址 01-01-09
正如你所看到的那样,它在退出第二个嵌套循环后正在插入/ divs。 我显然做错了什么,但我不知道是什么。 有任何想法吗?
编辑:如果放
jQuery("#active_list").append("");
在它自己的线上,它立即关闭div。 所以我猜我需要用jquery构建一个div元素然后打包然后追加我的div元素。
我对你的问题的建议
jQuery(text).find("person").each(function(){ var html; html = jQuery(this).find("Name").text() + " at "; jQuery(this).find("location").each(function(){ html += jQuery(this).find("locationName").text() + " on "; }); html += jQuery(this).find("date").find("startDate").text(); jQuery("#active_list").append("" + html + ""); });
这应该工作。 你试着微调它。 您的脚本无法工作的原因是因为jquery将每个字符串转换为一个对象。
在Wordpress中使用jQuery的一个小技巧:将它包含在一个函数中。 它将允许您使用熟悉的$函数,它将阻止您使用变量污染全局命名空间。
例如,您的代码可以重写为:
(function($) { ... (code with $) ... })(jQuery);
至于你的问题的答案,如果使用this
变量,嵌套的each
es在jQuery中都不起作用。 要解决您的问题,请尝试使用each
的完整样式:
$(...).each(function(i, val1) { $(...).each(function(j, val2) { ... } });
并使用val1
和val2
而不是this
。