如何在不定义变量

时间:2016-04-25 17:55:30

标签: javascript createelement

我很确定我已经知道了答案,但我想要一个解释。

我想创建和追加一个元素,而不必在变量中定义它(这对我来说似乎是一种浪费,并且是不必要的)。

var errorMessage = document.getElementById("errorMessage");

 errorMessage.innerHTML = "";

errorMessage.appendChild(document.createElement('p').appendChild(document.createTextNode("Due to an egg allergy, your child will NOT receive the flu vaccine.")));

所以这实际上将文本节点附加到errorMessage元素中,但是不会生成' p'标签

我认为你必须定义一个变量来创建一个新的元素,这种方式更加优雅,这是荒谬的。我还没能在网上找到任何关于此事的信息。有没有人知道这种方式的工作方式我喜欢或可能知道为什么它不会以这种方式工作?

3 个答案:

答案 0 :(得分:5)

appendChild返回附加的子项。所以我想你想要

var text = "Due to an egg allergy, your child will NOT receive the flu vaccine.";
document.getElementById("errorMessage")
  .appendChild(document.createElement('p'))
  .appendChild(document.createTextNode(text));

答案 1 :(得分:0)

我不确定我理解您要实现的目标,但如果您只想将innerHTML元素的HTML设置为某些HTML,为什么不使用errorMessage.innerHTML = '<p>Due to an egg allergy, your child will NOT receive the flu vaccine.</p>'; 属性呢?

// My original code (using find)
$cursor = $collection->find(array("organization" => $curr_org['organization'], "role" => array('$exists' => true)));

// The new code (using distinct)
$cursor = $collection->distinct('role', array("organization" => $curr_org['organization'], "role" => array('$exists' => true)));
foreach($cursor as $curr_org){
    echo '<ul>';
         echo '<li>';
              echo $curr_org['role'];
         echo '</li>';
    echo '</ul>';
}

答案 2 :(得分:0)

如果您不止一次做某事,请创建一个抽象

function createP(text) {
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(text));
  return p;
}

document.body.appendChild(createP('hello world'));