gpt4 book ai didi

函数内 while 循环内的 Javascript If 语句中断页面

转载 作者:行者123 更新时间:2023-12-02 17:03:38 26 4
gpt4 key购买 nike

我对 Javascript 非常非常新手,但当我在函数中添加一个简单的 if 语句时,我似乎破坏了我的页面/函数。

工作完美:

$(function() {
var i = 0;
while (i <= 71) {
i++;
var linky = "modal" + i;
$( "#dialog-form" + i ).dialog({
autoOpen: false,
height: 400,
width: 475,
linky: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
linky: false;
}
},
close: function() {
linky: false;
}
});
}

中断页面:

$(function() {
var i = 0;
while (i <= 71) {
i++;
var linky = "modal" + i;
$( "#dialog-form" + i ).dialog({
autoOpen: false,
if( i <= 8 ) {
height: 300,
width: 350,
} else {
height: 400,
width: 475,
}
linky: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
linky: false;
}
},
close: function() {
linky: false;
}
});
}

如果 id 小于 9,只是尝试减小高度和宽度,但我似乎无法在不破坏功能的情况下做到这一点。

最佳答案

您不仅仅是将 if 放入函数中,而是将 if 放入 JavaScript 对象的中间。

这是一个有效的 JavaScript 对象:

{
key1: 1,
key2: 2,
key2: 3
}

但是您无法添加控制流语句(例如 ifforwhileswitch)像这样在这个对象的中间:

{
key1: 1,
if (true) { // ERROR
key2: 2,
}
key2: 3
}
<小时/>

你可以通过以下方式实现你想要的

  1. 首先创建没有高度宽度的选项对象。
  2. 然后执行 if 并为 heightwidth 添加正确的值。
  3. 然后调用$( "#dialog-form"+ i ).dialog(options):

像这样:

//STEP 1
var dialogOptions = {
autoOpen: false,
linky: true,
buttons: {
Cancel: function () {
$(this).dialog("close");
linky: false;
}
},
close: function () {
linky: false;
}
};
//STEP 2
if (i <= 8) {
dialogOptions.height = 300;
dialogOptions.width = 350;
} else {
dialogOptions.height = 400;
dialogOptions.width = 475;
}
//STEP 3
$("#dialog-form" + i).dialog(dialogOptions);

关于函数内 while 循环内的 Javascript If 语句中断页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25468155/

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