我有一個包含 3 個欄位的表單:
<form id="book-form">
<div >
<label for="title">Title</label>
<input type="text" name="title" placeholder="Enter a title">
</div>
<div >
<label for="author">Author</label>
<input type="text" name="author" placeholder="Enter the author of the book">
</div>
<div >
<label for="isbn">ISBN#</label>
<input type="text" name="isbn" placeholder="Enter the book isbn">
</div>
<button type="submit" >Add Book to store</button>
</form>
這是我正在檢索這些欄位的值,這些欄位將插入到 html 中各自的跨度中。
const title = document.getElementsByName('title')[0].value
const author = document.getElementsByName('author')[0].value
const isbn = document.getElementsByName('isbn')[0].value
現在我有三個跨度標簽,這些表單欄位的值應該被插入。
<span class="title">// the value of title</span>
<span class="author">// the value of author</span>
<span class="isbn">// the value of isbn</span>
現在我有一個函式來檢查從表單的欄位中檢索是否不為空(空),如果是這種情況,我想洗掉假定在 dom 中的跨度。
function insertMe(fieldValue) {
if (fieldValue === "") {
// How to remove the span that it was suppose to go
} else {
return fieldValue
}
}
uj5u.com熱心網友回復:
不清楚您如何呼叫insertMe,并且該函式的名稱具有誤導性,因為您只是洗掉元素,而不是添加它們。
我會這樣處理。
單擊按鈕/onSubmit 時,呼叫該函式并用于querySelectorAll按類定位所有輸入。迭代它們,如果值是空字串,remove則其類與輸入名稱匹配的跨度,否則將跨度的文本內容設定為輸入值。
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
const inputs = document.querySelectorAll('.form-control');
inputs.forEach(({ name, value }) => {
const el = document.querySelector(`span.${name}`);
if (el && !value) {
el.remove();
} else {
el.textContent = value;
}
});
}
<input type="text" class="form-control" name="title" placeholder="Enter a title">
<input type="text" class="form-control" name="author" placeholder="Enter an author">
<input type="text" class="form-control" name="isbn" placeholder="Enter an ISBN number">
<button>Click</button>
<br/><br/>
<span class="title">Title</span><br/>
<span class="author">Author</span><br/>
<span class="isbn">ISBN</span><br/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318143.html
標籤:javascript dom
