我正在尝试在表单提交上创建一个JSON对象以传递给Perl.我有几个嵌套的divs和uls li允许jQuery-ui可排序的排序.
为了能够保存已排序的lis(遍布几个divs),我编写了以下代码:
jQuery("form[name='editorview']").submit(function(event) {
event.preventDefault();
var values = '{ ';
jQuery(this).find(".div_abcd").each(function(){
values += '"'+this.id+'": [';
jQuery(this).find("div[id^='CONT']").each(function(){
values += '{"'+this.id+'": [';
jQuery(this).find("li").each(function(){
if (jQuery(this).not("class='placeholder'")){
values += '"'+this.id+'",';
} else {
values +='"placeholder",';
}
});
values = values.slice(0, -1); //removing trailing ,
values +=']},';
});
values = values.slice(0, -1); //removing trailing ,
values += '],';
});
values = values.slice(0, -1); //removing trailing ,
values += '}';
jQuery("#order").val(values);
document.editorview.submit();
});
Run Code Online (Sandbox Code Playgroud)
div班级最多4 秒,div_abcd但不一定包括其他divs.在这种情况下,我遇到的问题是第二个 从第5行values = values.slice(0, -1);移除了开口[.
有没有办法让elseif jQuery(this).find("div[id^='CONT']").each(function(){与任何东西都不匹配.我尝试使用,.not()但它没有用.
编辑:
即使我的问题得到解决,我仍然想知道是否有可能知道每个()甚至一次都没有运行.
第二编辑:
一切都清楚了.谢谢.
我敢打赌,有一个比循环更好的方法但是一开始:不要手动构建字符串!
var values = {};
jQuery(".div_abcd", this).each(function(){
var a = values[this.id] = [];
jQuery("div[id^='CONT']", this).each(function(){
var obj = {};
obj[this.id] = jQuery("li", this).map(function() {
if (jQuery(this).is(".placeholder")){
return "placeholder";
}
return this.id;
}).get();
a.push(obj);
});
});
values = JSON.stringify(values);
Run Code Online (Sandbox Code Playgroud)
更新:您还必须使用is()而不是not()
检查这个演示.
更新以回答您的问题:
您始终可以使用length以下方法检查选择的元素数量:
var $elements = jQuery(this).find("div[id^='CONT']");
if($elements.length > 0) {
$elements.each(...);
}
else {
// something else
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |