gpt4 book ai didi

如果没有找到结果,Jquery every() 回退

转载 作者:行者123 更新时间:2023-12-01 02:49:08 26 4
gpt4 key购买 nike

我正在尝试在表单提交上创建一个 JSON 对象以传递给 Perl。我有几个嵌套的 divulli 来允许 jQuery-ui 可排序。

为了能够保存排序后的 li(分布在多个 div 上),我编写了以下代码:

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();
});

div_abcd 类最多有 4 个 div,但它们不一定包含其他 div。在这种情况下,我遇到的问题是第二个 values = value.slice(0, -1); 删除了第 5 行的开头 [

有没有办法让 else if jQuery(this).find("div[id^='CONT']").each(function(){ 不匹配任何内容。我尝试使用 .not() 但没有成功。

编辑:

即使我的问题解决了,我仍然想知道是否有可能知道each()何时没有运行一次。

第二次编辑:

现在一切都清楚了。谢谢。

最佳答案

我敢打赌有比循环更好的方法,但首先:不要手动构建字符串!

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);

更新:您还必须使用is()而不是 not()

引用: map , get , JSON

检查这个DEMO .

更新以回答您的问题:

您始终可以使用length检查选择了多少个元素。 :

var $elements = jQuery(this).find("div[id^='CONT']");
if($elements.length > 0) {
$elements.each(...);
}
else {
// something else
}

关于如果没有找到结果,Jquery every() 回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4546907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com