【发布时间】: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