如何从其文本节点或文本内容中获取跨度?

萨希什

我有一个包含 3 个字段的表单:

            <form id="book-form">
            <div class="form-group">
              <label for="title">Title</label>
              <input type="text" name="title" class="form-control" placeholder="Enter a title">
            </div>
            <div class="form-group">
              <label for="author">Author</label>
              <input type="text" name="author" class="form-control" placeholder="Enter the author of the book">
            </div>
            <div class="form-group">
              <label for="isbn">ISBN#</label>
              <input type="text" name="isbn" class="form-control" placeholder="Enter the book isbn">
            </div>
            <button type="submit" class="btn btn-primary btn-block">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
}

}

安迪

不清楚您如何调用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/>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章