我必须使用香草JavaScript的项目。我有几个功能,其中之一是打开菜单的按钮。它在目标id存在的页面上工作,但在id不存在的页面上导致错误。在那些页面上,函数找不到id,我收到一个“不能读取属性'addEventListener'的空”错误,我的其他函数都不起作用。
下面是打开菜单的按钮的代码。
function swapper() {
toggleClass(document.getElementById('overlay'), 'open');
}
var el = document.getElementById('overlayBtn');
el.addEventListener('click', swapper, false);
var text = document.getElementById('overlayBtn');
text.onclick = function(){
this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
return false;
};
我该怎么处理呢?我可能需要将这段代码全部包装在另一个函数中,或者使用if/else语句,以便它只搜索特定页面上的id,但不确定。
我有一组引语和人名。我使用更新按钮更新与特定名称相关联的最后引用,但单击更新按钮它不更新。我包括下面的代码server.js文件和外部js文件(main.js)。
main.js(外部js)
var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {
fetch('quotes', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'name': 'Muskan',
'quote': 'I find your lack of faith disturbing.'
})
})var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {
fetch('quotes', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'name': 'Muskan',
'quote': 'I find your lack of faith disturbing.'
})
})
.then(res =>{
if(res.ok) return res.json()
})
.then(data =>{
console.log(data);
window.location.reload(true);
})
})
}
server.js文件
app.put('/quotes', (req, res) => {
db.collection('quotations').findOneAndUpdate({name: 'Vikas'},{
$set:{
name: req.body.name,
quote: req.body.quote
}
},{
sort: {_id: -1},
upsert: true
},(err, result) =>{
if (err) return res.send(err);
res.send(result);
})
})