请参阅下面的编辑。 我正在尝试让一些 jquery 在我正在构建的 WordPress 插件中工作。 (在wordpress中使用jquery时,使用字符串'jQuery'代替'$'习惯用法,仅供引用)
示例 xml:
<person> <Name>Some Name</Name> <location> <locationName>One Address</locationName> </location> <date> <startDate>01-01-09</startDate> </date> </person>
sample jquery:
jQuery(text).find("person").each(function(){
jQuery("#active_list")
.append(
"<div id=\'Entry\'>"
+ jQuery(this).find("Name").text()
+ "<b> at </b>"
;
jQuery(this)
.find("location")
.each(function(){
jQuery("#active_list")
.append(
jQuery(this).find("locationName").text()
+ " <b> on </b>"
)
;
})
;
jQuery("#active_list")
.append(
jQuery(this).find("date").find("startDate").text()
+ "</div>"
)
;
});
然后产生了错误的标记:
<div id="Entry"> Some Name<b> at </b></div>One Address <b> on </b>01-01-09
as you can see it is inserting /divs right after it exits the second nested loop. I'm obviously doing something wrong but I don't know what. Any ideas?
EDIT: If put
jQuery("#active_list").append("<div id=\'ActivityEntry\'>");
在它自己的行上,它会立即关闭 div。所以我猜我需要用 jquery 构建一个 div 元素,然后打包它,然后附加我的 div 元素。
最佳答案
在 Wordpress 中使用 jQuery 的一个小技巧:将其包含在一个函数中。它将允许您使用熟悉的 $ 函数,并防止您用变量污染全局命名空间。
例如,您的代码可以重写为:
(function($) {
... (code with $) ...
})(jQuery);
至于您的问题的答案,如果您使用 this
变量,则嵌套的 each
在 jQuery 中不起作用。要解决您的问题,请尝试使用 each
的完整样式:
$(...).each(function(i, val1) {
$(...).each(function(j, val2) { ... }
});
并使用val1
和val2
而不是this
。
关于jquery 嵌套每个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1005006/