作为参数传递时,document.createElement的行为是什么? [英] What is the behavior of document.createElement when passed as an argument?

查看:77
本文介绍了作为参数传递时,document.createElement的行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试传递由 document.createElement 方法创建的元素时,我们会遇到异常结果:

When attempting to pass an element created by the document.createElement method, we encounter unusual results:

var Todo = (function () {
  return {
    items: [],
    addItem: function () {
      var task = document
        .querySelector('#top-todo')
        .value
        .trim()
      if (task !== '') {
        this.items.push({ task, complete: false })
        document.querySelector('#top-todo').value = ''
        console.log('Added item: ' + task)
        var newTodo = document.createElement('li')
          .appendChild(document.createElement('p'))
          .appendChild(document.createTextNode(task))
        document.querySelector('#todo-list').appendChild(newTodo)
      }
    }
  }
})()

<div>
  <ul id="todo-list">
    <li>
      <input id="top-todo" placeholder="I need to..." type="text" />
    </li>
  </ul>
  <input onclick="Todo.addItem()" type="button" value="add" />
</div>

我们只看到textNode元素被追加到 #todo-list 元素。这种行为的原因是什么?是否有一种有效的方法可以使用该方法作为追加或插入的参数?

Rather than a total failure or typeError we see only the textNode element being appended to the #todo-list element. What is the cause of this behavior? And is there a valid way to use the method as an argument to append or insert?

推荐答案

Node.appendChild


返回的值是附加的子项。

The returned value is the appended child.

您可以链接 .parentElement .parentElement ,设置为 li 子元素的嵌套元素的数量,为 .appendChild()调用以获取 document.createElement('li') newTodo

You can chain .parentElement.parentElement, the number of nested elements set as child elements of li, to last .appendChild() call to get reference to document.createElement('li') at newTodo

var Todo = (function () {
  return {
    items: [],
    addItem: function () {
      var task = document
        .querySelector('#top-todo')
        .value
        .trim()
      if (task !== '') {
        this.items.push({ task, complete: false })
        document.querySelector('#top-todo').value = ''
        console.log('Added item: ' + task)
        var newTodo = document.createElement('li')
          .appendChild(document.createElement('p'))
          .appendChild(document.createTextNode(task))
          .parentElement.parentElement                    
        document.querySelector('#todo-list').appendChild(newTodo)
      }
    }
  }
})()

<div>
  <ul id="todo-list">
    <li>
      <input id="top-todo" placeholder="I need to..." type="text" />
    </li>
  </ul>
  <input onclick="Todo.addItem()" type="button" value="add" />
</div>

这篇关于作为参数传递时,document.createElement的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆