gpt4 book ai didi

javascript - Uncaught ReferenceError : questions is not defined

转载 作者:行者123 更新时间:2023-11-28 07:58:36 24 4
gpt4 key购买 nike

在其他函数中使用全局变量时,我收到 Uncaught ReferenceError: questions is not Defined 错误。

JavaScript 代码:

$(function() {
var dialog,total_que=0;
var questions = { name:{}, type:{}, options:{}}

function addQuestion() {
var que = new Array();
var option = new Array();
var new_element_label;
var new_element = "";
var i=0;
form_fields = form[0].elements.length;

if(form_fields<=2){
que['name'] = form[0].elements[0].value;
que['type'] = form[0].elements[1].value;
}
else
{
que['name'] = form[0].elements[0].value;
que['type'] = form[0].elements[1].value;
for(i=0;i<(form_fields-3);i++){
option[i] = form[0].elements[i+3].value;
}
}

switch(que['type']){
case 'text':
var new_element = '<input type="text" name="name" placeholder="'+que['name']+'">';
break;
default:
break;
}
new_element_label = '<label for="name">'+que['name']+'</label><br>';
new_element_label += '<div for="text">';
new_element += '</div>';
$('#add_polling_form fieldset').append("<br>"+new_element_label+new_element);
dialog.dialog( "close" );
form[0].reset();
questions['name'][total_que] = que['name'];
questions['type'][total_que] = que['type'];
questions['options'][total_que] = option;
total_que++;
console.log(questions);
}

console.log(questions);
dialog = $("#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Add Question": addQuestion,
Cancel: function() {
$('#que_option_val').html('');
dialog.dialog( "close" );
form[0].reset();
}
},
close: function() {
$('#que_option_val').html('');
dialog.dialog( "close" );
form[0].reset();
}
});
form = dialog.find( "form" ).on("submit", function( event ) {
event.preventDefault();
});
$( "#create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
});

function add_que_option(que_type){
var que_type = que_type;
switch(que_type){
case 'text':
$('#que_option_val').html('');
break;
default:
$('#que_option_val').html('<input type="button" class="ui-button" value="Add More Option" onclick="add_option();">')
$('#que_option_val').append("<input type='text' placeholder='Option for Question'>");
}
}
function add_option(){
$('#que_option_val').append("<input type='text' placeholder='Option for Question'>");
}
function save_form(){
console.log(questions);
}

当我调用 addQuestion() 函数时,值被插入到选项数组中。但是当我调用 save_form() 时,它在控制台中给我这样的错误。

Uncaught ReferenceError: questions is not defined 
save_form
onclick

最佳答案

变量 questions 是位于顶部 $(...) 调用内部的匿名函数的本地变量。 save_form() 是在该函数外部定义的,因此这些局部变量对其都不可见。

您应该将 save_form 移至 $(function() { ... } 内部,或将 questions 的声明移至其外部。

关于javascript - Uncaught ReferenceError : questions is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717882/

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