为什么不JavaScript函数创建一个HTML元素?

问题描述 投票:0回答:2

我有一个方法,这是为了另一个DIV中创建的div ...但是它不会工作...

这里是方法:

populateSquares(){
    let relatedTagToPopulation = document.getElementById("questionp");
    let whatTextIs = relatedTagToPopulation.textContent;
    for (let u=0;u<this.stemQuestions.length;u++){
        if (this.stemQuestions[u]==whatTextIs){
            var populateSquaresPertinentInt = u;
        }
    }
    for  (let i=0;i<this.stemAnswers.length;i++){
        if (i==populateSquaresPertinentInt){
            let numberOfSquaresToAdd = this.stemAnswers[i].length;
            for (let j=0;j<numberOfSquaresToAdd;j++){
                let elToAdd = document.createElement("<div id='ans"+j+"' class='lans'></div>"); 
                let elToAddInto = document.getElementById("answeri"); 
                elToAddInto.appendChild(elToAdd); 
            }
        }
    }
}

它给了这个错误...

Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('<div id='ans0' class='lans'></div>') is not a valid name.
javascript html dom
2个回答
2
投票

如果您使用JavaScript,你应该遵循的文件:https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement,在这里:CreateElement with id?

let elToAdd = document.createElement('div')
// then call `elToAdd.xxxx` to add attributes or do other operation on the element
elToAdd.setAttribute("id", "ans" + i);
// ... more

如果你使用jQuery,您可以使用:

let elToAdd = jQuery("<div id='ans"+j+"' class='lans'></div>")

1
投票

Three Ways to Create Tags

下面的例子都做同样的事情:✱ 创建一个类的<article>标签:.post并把它添加到<main id="main">标签。 ✱有一个例外见#2 .innerHTML


document.createElement(tagName)

唯一的参数是一个tagName(来自"DIV""SPAN""IFRAME"等)。一旦创建,它需要被添加到DOM:

const post = document.createElement("ARTICLE");
post.className = "post";
document.getElementById('main').appendChild(post);

这是一个古老而又稳定的方法,但它需要两条线来创建一个准系统标签。更多的代码是需要分配的属性和内容。


.innerHTML += htmlString

此属性将解析标签(一个或多个)进行有针对性的标签中指定的字符串的。如果=运营商使用有针对性的标签的所有内容将被替换为htmlString。如果使用+=运营商的htmlString将被追加到目标标签中的内容。

document.querySelector('main').innerHTML += `<article class='post'></article>`;

这种模式是简单和通用性。在一行中的多个标签可以与属性和内容创建。它局限于要么改写内容:=或追加内容:+=

✱Edit:Kaiido已通知我,因此,如果您担心事件绑定或引用不使用它.innerHTML将取代一切。请参阅下面的评论。


.insertAdjacentHTML(position, htmlString)

这是对类固醇.innerHTML。它会插入前/后/中/有针对性的标签给定的htmlString之外。第一个参数是的四根弦的是确定相对于目标的标记插入的位置之一:

"beforebegin" <div id="target"> "afterbegin" text content "beforeend" </div> "afterend"

第二个参数是要插入的htmlSting

document.getElementsByTagName('MAIN')[0].insertAdjacentHTML('afterbegin', `
  <article class='post'></article>
`);                    

我不能按照你的代码,但它应该是一个方法?因此,演示了一个对象调用populate并有创建对象和继承documentSection()方法.createSection()一个工厂函数调用populate

演示

let text = ['post 1', 'post 2', 'post 3'];
let archives = ['document 1', 'document 2', 'document 3'];

const populate = content => ({
  createSections: () => {
    let idx = 0;
    const target = document.querySelector("main");
    /* 
    Pattern 1 - document.createElement(tagName)
    */
    const section = document.createElement('SECTION');
    section.id = content.title;
    target.appendChild(section);
    /*
    Pattern 2 - .innerHTML += htmlString
    */
    section.innerHTML += `<h2>${content.title}</h2>`;
    for (let text of content.text) {
      idx++;
      /*
      Pattern 3 - .insertAdjacentHTML(position, htmlString)
      */
      section.insertAdjacentHTML('beforeend', `<article id="${content.title}-${idx}" class="t">${text}</article>`);
    }
  }
});

const documentSection = (title, text) => {
  let content = {
    title: title,
    text: text
  };
  return Object.assign(content, populate(content));
};

const post = documentSection('Post', text);
const archive = documentSection('Archive', archives);

post.createSections();
archive.createSections();
main {
  display: table;
  border: 3px ridge grey;
  padding: 2px 10px 10px;
}

h1 {
  font: 900 small-caps 1.5rem/1 Tahoma;
  margin-bottom: 8px
}

h2 {
  font: 700 small-caps 1.2rem/1 Tahoma;
  margin-bottom: 8px
}

section {
  border: 2px solid #000;
  padding: 2px 8px 8px;
}

article {
  font: 400 1rem/1.25 Arial;
}

.t::before {
  content: attr(id)': ';
  font-weight: 700;
}
<main>
  <h1>Documents</h1>
</main>
© www.soinside.com 2019 - 2024. All rights reserved.