當我在不輸入任何文本的情況下單擊“添加注釋”按鈕時,我不希望本地存盤添加一個空字串,而是希望彈出一條警告訊息說“輸入文本”。我嘗試了幾種方法嘗試將警報功能放置在不同的點,但顯示一個錯誤,說“無法讀取 null 的屬性”。請建議一些代碼。謝謝你。[1]:https://i.stack.imgur.c
console.log("Add Notes");
showNotes();
// If user adds a note, add it to the localStorage
let btnBag = document.getElementById("addBtn");
btnBag.addEventListener("click", function(e) {
let txtBag = document.getElementById("addTxt");
let notesBag = localStorage.getItem("notes");
if (notesBag == null) {
notesBag = [];
} else {
notesBag = JSON.parse(notesBag);
}
notesBag.push(txtBag.value);
localStorage.setItem("notes", JSON.stringify(notesBag));
txtBag.value = "";
// showAlert();
showNotes();
});
//Function to display elements located in localStorage
function showNotes(){
// place the notes array in an element called notesBag
let notesBag = localStorage.getItem("notes");
if (notesBag == null) {
objBag = [];
} else {
objBag = JSON.parse(notesBag);
}
// create a blank string named html
let html = '';
// For the notesBag(which is parsed and placed into the objBag element) create forEach loop so that each notes stored in array is shown seperateley
objBag.forEach(function (element,index) {
html =`
<div id="notes" >
<div style="width: 18rem;">
<div >
<h5 >Note ${index 1}</h5>
<p >${element}</p>
<button id = "${index} onclick = "deleteNote(this.id)" >Delete Note</button>
</div>
</div>
</div> `;
});
let notesElem = document.getElementById("notes");
if(objBag.length != 0){
notesElem.innerHTML = html;
} else {
notesElem.innerHTML = `Add Something for displaying the note`;
}
};
//Delete a note
/* // Function to delete a note
function deleteNote(index) {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
} */
// let search = document.getElementById('searchTxt');
// search.addEventListener("input", function(){
// let inputVal = search.value.toLowerCase();
// // console.log('Input event fired!', inputVal);
// let noteCards = document.getElementsByClassName('noteCard');
// Array.from(noteCards).forEach(function(element){
// let cardTxt = element.getElementsByTagName("p")[0].innerText;
// if(cardTxt.includes(inputVal)){
// element.style.display = "block";
// }
// else{
// element.style.display = "none";
// }
// // console.log(cardTxt);
// })
// })
/*Further Features:
1. Add Title
2. Mark a note as Important
3. Separate notes by user
4. Sync and host to web server
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Practice code</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.navbar-brand {
color: red;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-dark ">
<a class="navbar-brand" href="#">Multiple Notes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a href="#">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search"
aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search
</button>
</form>
</div>
</nav>
<div class="container my-3">
<h1>Take Notes Here</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Add Note</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3"></textarea>
</div>
<button class="btn btn-primary" id="addBtn" onsubmit="showAlert()">Add Note</button>
</div>
</div>
<hr>
<h1>Your Notes</h1>
<hr>
<div id="notes" class=" row container-fluid">
<!-- <div style="width: 18rem;">
<div >
<h5 >First Note</h5>
<p ></p>
<a href="#" >Delete</a>
</div>
</div> -->
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM B07jRM"
crossorigin="anonymous"></script>
<script src="harry js files/practice.js"></script>
</html>
om/ZKITG.png
uj5u.com熱心網友回復:
您將必須添加一個空檢查。請檢查以下代碼以供參考。
let btnBag = document.getElementById("addBtn");
btnBag.addEventListener("click", function(e) {
let txtBag = document.getElementById("addTxt");
if(txtBag && txtBag.value !="" && txtBag.value !=undefined ){
let notesBag = localStorage.getItem("notes");
if (notesBag == null) {
notesBag = [];
} else {
notesBag = JSON.parse(notesBag);
}
notesBag.push(txtBag.value);
localStorage.setItem("notes", JSON.stringify(notesBag));
txtBag.value = "";
// showAlert();
showNotes();
}
else{
alert('enter a text');
}
});
uj5u.com熱心網友回復:
您需要添加一個空支票,然后發出警報。(標有****)
console.log("Add Notes");
showNotes();
// If user adds a note, add it to the localStorage
let btnBag = document.getElementById("addBtn");
btnBag.addEventListener("click", function(e) {
let txtBag = document.getElementById("addTxt");
if (txtBag.value == "") { //****
alert("Empty Note");
return
}
let notesBag = localStorage.getItem("notes");
if (notesBag == null) {
notesBag = [];
} else {
notesBag = JSON.parse(notesBag);
}
notesBag.push(txtBag.value);
localStorage.setItem("notes", JSON.stringify(notesBag));
txtBag.value = "";
// showAlert();
showNotes();
});
//Function to display elements located in localStorage
function showNotes() {
// place the notes array in an element called notesBag
let notesBag = localStorage.getItem("notes");
if (notesBag == null) {
objBag = [];
} else {
objBag = JSON.parse(notesBag);
}
// create a blank string named html
let html = '';
// For the notesBag(which is parsed and placed into the objBag element) create forEach loop so that each notes stored in array is shown seperateley
objBag.forEach(function(element, index) {
html = `
<div id="notes" >
<div style="width: 18rem;">
<div >
<h5 >Note ${index 1}</h5>
<p >${element}</p>
<button id = "${index} onclick = "deleteNote(this.id)" >Delete Note</button>
</div>
</div>
</div> `;
});
let notesElem = document.getElementById("notes");
if (objBag.length != 0) {
notesElem.innerHTML = html;
} else {
notesElem.innerHTML = `Add Something for displaying the note`;
}
};
//Delete a note
/* // Function to delete a note
function deleteNote(index) {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
} */
// let search = document.getElementById('searchTxt');
// search.addEventListener("input", function(){
// let inputVal = search.value.toLowerCase();
// // console.log('Input event fired!', inputVal);
// let noteCards = document.getElementsByClassName('noteCard');
// Array.from(noteCards).forEach(function(element){
// let cardTxt = element.getElementsByTagName("p")[0].innerText;
// if(cardTxt.includes(inputVal)){
// element.style.display = "block";
// }
// else{
// element.style.display = "none";
// }
// // console.log(cardTxt);
// })
// })
/*Further Features:
1. Add Title
2. Mark a note as Important
3. Separate notes by user
4. Sync and host to web server
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Practice code</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.navbar-brand {
color: red;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-dark ">
<a class="navbar-brand" href="#">Multiple Notes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a href="#">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search"
aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search
</button>
</form>
</div>
</nav>
<div class="container my-3">
<h1>Take Notes Here</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Add Note</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3"></textarea>
</div>
<button class="btn btn-primary" id="addBtn" onsubmit="showAlert()">Add Note</button>
</div>
</div>
<hr>
<h1>Your Notes</h1>
<hr>
<div id="notes" class=" row container-fluid">
<!-- <div style="width: 18rem;">
<div >
<h5 >First Note</h5>
<p ></p>
<a href="#" >Delete</a>
</div>
</div> -->
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM B07jRM"
crossorigin="anonymous"></script>
<script src="harry js files/practice.js"></script>
</html>
uj5u.com熱心網友回復:
您可以檢查未定義和空字串。
let btnBag = document.getElementById("addBtn");
btnBag.addEventListener("click", function (e) {
let txtBag = document.getElementById("addTxt");
// Check for undefined and empty string, make sure user is
// not able to send empty white spaces
if(txtBag.value === undefined || txtBag.value.trim() === '') {
alert('Please enter text to add note');
return;
}
let notesBag = localStorage.getItem("notes");
if (notesBag == null) {
notesBag = [];
} else {
notesBag = JSON.parse(notesBag);
}
notesBag.push(txtBag.value);
localStorage.setItem("notes", JSON.stringify(notesBag));
txtBag.value = "";
// showAlert();
showNotes();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477639.html
標籤:javascript
上一篇:正則運算式驗證數字和字母
下一篇:從請求中獲取資料到主執行緒
