【问题标题】:JavaScript Vairable UndefinedJavaScript 变量未定义
【发布时间】:2021-08-05 04:38:38
【问题描述】:

这是html文件,它并不重要

<body>
        <!-- Select Radio Button -->
        <label for="radio1">Select</label>
        <input type="radio" name="radio1" id="radio1"  >
        <!-- Multi-Select Radio Button -->
        <label for="radio2"  >Multi-Select</label>
        <input type="radio" name="radio1" id="radio2" >
        <br>
        <!-- Items -->
        <label for="radio2">Item 1</label>
        <input type="radio" name="item" id="item0" value="item1">
        <label for="radio2">Item 2</label>
        <input type="radio" name="item" id="item1"  value="item2">
        <label for="radio2">Item 3</label>
        <input type="radio" name="item" id="item2" value="item3">
        <label for="radio2">Item 4</label>
        <input type="radio" name="item" id="item3" value="item4">
        <button type="submit" class="btn " onclick="handling_dbs()">Submit</button>
</body>
<script src="./index.js"></script>

现在是 index.js 文件

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/pro',{useNewUrlParser:true}); 
var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error'))
var selectionSchema = new mongoose.Schema({
    selection_type : {type:String, required:true},
    selected : {type:String, required:true}
})

                                        

var selections =  mongoose.model('selection',selectionSchema);
console.log(selections)  //Added this to check what's inside the selections variable

function handling_dbs(){ 
     console.log(selections) //Added this to check what's inside the selections variable
    if(document.getElementById('radio1').checked){
        let length=4;
        for(let i=0;i<length;i++){
            if(document.getElementById(`item${i}`).checked){
                let selected_item = document.getElementById(`item${i}`).value;
            }
        }
        
        let doc = new selections({
            selection_type:'Select',
            selected:   `${selected_item}`
        });
        doc.save();
        console.log('Yes')
    }
}

现在,当我尝试在函数内部访问它时,它是未定义的,当我明确定义它时。 为什么我不能在函数内部访问它,它显然是一个全局变量。

【问题讨论】:

  • 哪个变量未定义?在哪个函数中 - 大概在handling_dbs
  • 选择变量
  • 控制台显示了什么?记住不是每个人都使用过 Mongoose - 它可以是异步的吗?
  • 它揭示了函数之外的内容

标签: javascript html mongoose


【解决方案1】:

我认为 mongoose.connect 是一个异步函数,所以“mongoose.model('selection',selectionSchema);”的值尚不可用,当您将其分配给选择常量时。 将 selections 常量的初始化移动到 handling_dbs() 函数中应该可以解决该问题。 更复杂的解决方案是等到建立数据库连接,然后才让点击监听器工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2018-08-06
    • 2012-01-16
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多