简体   繁体   English

通过JavaScript在div中添加元素的问题

[英]Problems by adding elements in a div via javascript

I'm working on a upload formula, where the user can click on a "add" button, a "select file button" and a "title field" will show up then. 我正在处理一个上传公式,用户可以单击“添加”按钮,然后显示“选择文件按钮”和“标题字段”。

If the user clicks again on the "add button", a new button and field show up and so on and so forth. 如果用户再次单击“添加按钮”,则会显示一个新的按钮和字段,依此类推。

My problem: I need those elements in a div, to be able to style and change them a bit. 我的问题:我需要div中的那些元素,以便能够对其进行样式设置和更改。

Adding the elements do work but for a reason, adding a div doesn't work, and haven't figured out, what do to. 添加元素确实有效,但是出于某种原因,添加div不起作用,也没有弄清楚该怎么做。

Here is my code: 这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <title>TEST1</title>
    <meta charset="UTF-8"/>
  </head>

  <body>

    <div id="media">
      <form>
        <div>
          <div id="container">&nbsp;</div>
          <input type="button" value="add" id="add" />
        </div>
      </form>
    </div>


  </body>

JavaScript Code JavaScript代码

  <script>
    window.addEventListener("load", function()
    {
      document.getElementById("add").addEventListener("click", function()
      {
        // Create a div
        var container = document.createElement("div");
        container.setAttribute("class", "new_container[]");

        // Create a file input
        var file = document.createElement("input");
        file.setAttribute("type", "file");
        file.setAttribute("name", "sel_ad_file[]");

        // Create a break
        var br = document.createElement("br");

        // Create a text input
        var text = document.createElement("input");
        text.setAttribute("type", "text");
        text.setAttribute("name", "ad_file_title[]");
        text.setAttribute("placeholder", "File Title");


        // add the file and text to the div
        container.appendChild(file);
        container.appendChild(br);
        container.appendChild(text);

        //Append the div to the container div
        document.getElementById("media").appendChild(container);
      });
    });
  </script>

CSS Code CSS代码

<style>
* {margin: 0; padding: 0; font-family: ubuntu;}    
body
{
  overflow: hidden;
  background-color: rgba(75,75,75);
  z-index: -10;
}
#media
{
  width: 350px;
  height: 100%;
  top: 0px;
  left: 0px;
  position: absolute;
  background-color: rgba(30,30,30);
  float: left;
}
#media input[type="button"]
{
  width: 75px;
  height: 25px;
  top: 5px;
  left: 355px;
  position: absolute;
  color: orange;
  border-style: none;
  background-color: rgba(40,40,40);
  cursor: pointer;
}
#media input[type="button"]:hover
{
  background-color: rgba(50,50,50)
}
.new_container
{
  width: 250px;
  height: 250px;
  top: 0px;
  left: 0px;
  background-color: rgba(35,35,35);
  position: absolute;
  z-index: 1;
  border-radius: 10px;
  float: left;
}
.new_container input[type="file"]
{
  width: 90%;
  height: 25px;
  transform: translate(-50%, -50%);
  background-color: orange;
  border-style: none;
  position: absolute;
  top: 0px;
  left: 50%;
  margin: 0px;
  padding: 0px;
  z-index: 2;
}
.new_container input[type="text"]
{
  width: calc(90% - 10px);
  height: 25px;
  background-color: rgba(35,35,35);
  border-style: none;
  transform: translate(-50%, -50%);
  border: solid 1px rgba(255,255,255,.5);
  padding-left: 5px;
  padding-right: 5px;
  border-radius: 3px;
  position: relative;
  top: 150px;
  left: 50%;
  margin: 0px;
  padding: 0px;
  z-index: 2;
}
</style>

. . .

</html>

  window.addEventListener("load", function() { document.getElementById("add").addEventListener("click", function() { // Create a div var container = document.createElement("div"); container.setAttribute("class", "new_container[]"); // Create a file input var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "sel_ad_file[]"); // Create a break var br = document.createElement("br"); // Create a text input var text = document.createElement("input"); text.setAttribute("type", "text"); text.setAttribute("name", "ad_file_title[]"); text.setAttribute("placeholder", "File Title"); // add the file and text to the div container.appendChild(file); container.appendChild(br); container.appendChild(text); //Append the div to the container div document.getElementById("media").appendChild(container); }); }); 
  * {margin: 0; padding: 0; font-family: ubuntu;} /*----------------------------------------------------------------------------*/ body { overflow: hidden; background-color: rgba(75,75,75); z-index: -10; } /*============================================================================*/ #media { width: 350px; height: 100%; top: 0px; left: 0px; position: absolute; background-color: rgba(30,30,30); float: left; } #media input[type="button"] { width: 75px; height: 25px; top: 5px; left: 355px; position: absolute; color: orange; border-style: none; background-color: rgba(40,40,40); cursor: pointer; } #media input[type="button"]:hover { background-color: rgba(50,50,50) } .new_container { width: 250px; height: 250px; top: 0px; left: 0px; background-color: rgba(35,35,35); position: absolute; z-index: 1; border-radius: 10px; float: left; } .new_container input[type="file"] { width: 90%; height: 25px; transform: translate(-50%, -50%); background-color: orange; border-style: none; position: absolute; top: 0px; left: 50%; margin: 0px; padding: 0px; z-index: 2; } .new_container input[type="text"] { width: calc(90% - 10px); height: 25px; background-color: rgba(35,35,35); border-style: none; transform: translate(-50%, -50%); border: solid 1px rgba(255,255,255,.5); padding-left: 5px; padding-right: 5px; border-radius: 3px; position: relative; top: 150px; left: 50%; margin: 0px; padding: 0px; z-index: 2; } 
  <html> <head> <title>TEST1</title> <meta charset="UTF-8"/> </head> <body> <div id="media"> <form> <div> <div id="container">&nbsp;</div> <input type="button" value="add" id="add" /> </div> </form> </div> </body> </html> 

Your problem is that the div's class doesn't match the css class meant for it. 您的问题是div的类与为其指定的css类不匹配。

Removing [] from the strings in your setAttribute parameters, allows for the divs to be styled appropriately. setAttribute参数中的字符串中删除[] ,可以为div设置适当的样式。

Removing the position:absolute; 移开position:absolute; from the .newcontainer and its children's css prevents them from (mostly) stacking on top of each other. 来自.newcontainer及其子级css的代码阻止了它们(大部分)彼此堆叠。

Then, removing the transform: translate(-50%, -50%); 然后,删除transform: translate(-50%, -50%); from the file input allows them to be completely visible instead of half of them being hidden on the left side of the screen. 从文件输入中可以使它们完全可见,而不是将它们的一半隐藏在屏幕的左侧。

After these edits, the divs and their inputs are pretty plainly visible. 完成这些编辑后,div及其输入便清晰可见。

I then removed overflow: hidden; 然后我删除了overflow: hidden; from body css, so that when too many divs are created to fit on the screen/frame, you can see them and confirm that they are all there. 从body CSS中获取,以便当创建的div太多而无法容纳在屏幕/框架上时,您可以看到它们并确认它们都在那里。

 window.addEventListener("load", function() { document.getElementById("add").addEventListener("click", function() { // Create a div var container = document.createElement("div"); container.setAttribute("class", "new_container"); // Create a file input var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "sel_ad_file"); // Create a break var br = document.createElement("br"); // Create a text input var text = document.createElement("input"); text.setAttribute("type", "text"); text.setAttribute("name", "ad_file_title"); text.setAttribute("placeholder", "File Title"); // add the file and text to the div container.appendChild(file); container.appendChild(br); container.appendChild(text); //Append the div to the container div document.getElementById("media").appendChild(container); }); }); 
 * {margin: 0; padding: 0; font-family: ubuntu;} /*----------------------------------------------------------------------------*/ body { background-color: rgba(75,75,75); z-index: -10; } /*============================================================================*/ #media { width: 350px; height: 100%; top: 0px; left: 0px; position: absolute; background-color: rgba(30,30,30); float: left; } #media input[type="button"] { width: 75px; height: 25px; top: 5px; left: 355px; position: absolute; color: orange; border-style: none; background-color: rgba(40,40,40); cursor: pointer; } #media input[type="button"]:hover { background-color: rgba(50,50,50) } .new_container { width: 250px; height: 250px; top: 0px; left: 0px; background-color: rgba(35,35,35); z-index: 1; border-radius: 10px; float: left; } .new_container input[type="file"] { width: 90%; height: 25px; background-color: orange; border-style: none; top: 0px; left: 50%; margin: 0px; padding: 0px; z-index: 2; } .new_container input[type="text"] { width: calc(90% - 10px); height: 25px; background-color: rgba(35,35,35); border-style: none; transform: translate(-50%, -50%); border: solid 1px rgba(255,255,255,.5); padding-left: 5px; padding-right: 5px; border-radius: 3px; position: relative; top: 150px; left: 50%; margin: 0px; padding: 0px; z-index: 2; } 
 <html> <head> <title>TEST1</title> <meta charset="UTF-8"/> </head> <body> <div id="media"> <form> <div> <div id="container">&nbsp;</div> <input type="button" value="add" id="add" /> </div> </form> </div> </body> </html> 

难以将唯一的事件侦听器添加到已创建的<div>通过 for 循环的元素</div><div id="text_translate"><p>我正在做一个项目来学习一些 JavaScript,目标是在单页 web 应用程序中动态提供电子邮件。 应用程序的HTML已经使用createElement JS方法创建。 到目前为止,我已经成功地显示了包含所有电子邮件的“收件箱”页面,如下图所示:</p><p> <a href="https://i.stack.imgur.com/V8cZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8cZq.png" alt=""></a></p><p> 我目前正在尝试通过使用 addEventListener 使这些单独的电子邮件中的每一个都可以点击。 我遇到的问题是,每当我单击任何一封电子邮件时,都会呈现收件箱中的第一个 email(id:1,主题:测试电子邮件),并且无法查看任何其他电子邮件。</p><p> <a href="https://i.stack.imgur.com/BBjQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBjQj.png" alt=""></a></p><p> 我可以看到相同的 email.id 被应用到所有创建的 div 的事件侦听器,尽管所有 div 都被正确创建,并包含来自相应电子邮件的所有信息。</p><p> 这是加载邮箱 JS,它呈现收件箱中的所有电子邮件:</p><pre> function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; // GET request fetch(`/emails/${mailbox}`).then(response => response.json()).then(emails => { // Print emails to console console.log(emails); // Iterate through each email for(var i = 0; i < emails.length; i++) { var email = emails[i]; // Create div and append email content to HTML var emaildiv = document.createElement('div'); emaildiv.style.borderStyle = 'solid'; emaildiv.style.borderColor = 'black'; emaildiv.style.borderWidth = '0.1rem'; emaildiv.style.borderRadius = '0'; emaildiv.style.marginBottom = '0.2rem'; emaildiv.style.padding = '0.3rem'; emaildiv.innerHTML = `<b>${email.sender}</b> --- ${email.subject}<br>${email.timestamp}`; // If individual email selected then view email emaildiv.addEventListener('click', () => view_email(email)); // Populate div HTML with emails document.querySelector('#emails-view').append(emaildiv); console.log(email.read); // Colour backgrounds based on whether emails have been read if (email.read == true) { emaildiv.style.backgroundColor = 'lightgrey'; } console.log(email); } });}</pre><p> 这是视图 email JS,它应该渲染个人 email 的 HTML:</p><pre> // View email function view_email(email) { console.log(email.id); // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'block'; // GET request fetch(`/emails/${email["id"]}`).then(response => response.json()).then(email => { // Create div, set class, and append email content to HTML var reademail = document.createElement('div'); reademail.innerHTML = ''; reademail.style.borderStyle = 'solid'; reademail.style.borderColor = 'black'; reademail.style.borderWidth = '0.1rem'; reademail.style.borderRadius = '0'; reademail.style.marginBottom = '0.2rem'; reademail.style.padding = '0.3rem'; reademail.innerHTML = ` <b>From:</b> ${email.sender}<br> <b>To:</b> ${email.recipients}<br> <b>Subject:</b> ${email.subject}<br> <b>Timestamp:</b> ${email.timestamp}<br> <button class="btn btn-sm btn-outline-primary" id="Reply">Reply</button> <hr> ${email.body}`; // Populate div HTML with emails document.querySelector('#single-view').append(reademail); // Mark unread emails as read if (email.read === 'false') { fetch(`/emails/${email}`, { method: 'PUT', body: JSON.stringify({ read: true }) }) } }); }</pre><p> 这是存储在 email GET 响应中的示例(虚拟数据):</p><pre> { "id": 1, "sender": "user@example.com", "recipients": ["user@example.com"], "subject": "Hello,": "body", "Hello, world:", "timestamp": "Oct 24 2020, 12:00 AM", "read": false, "archived": false }</pre><p> 我已经尝试将其他每封电子邮件的 ID 硬编码到视图 email JS 中,并且可以看到该功能按要求工作(显示电子邮件)。</p><p> 因此,我知道问题与上面的加载邮箱 JS 有关,并且可能与事件侦听器如何在 for 循环中应用有关。 如果有人可以阐明如何将唯一的事件侦听器应用于每个单独的 div,将不胜感激。</p><p> 谢谢!</p></div> - Difficulty adding unique event listener to created <div> elements via a for loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Javascript 中向 div 元素添加按钮的问题 - Problems with adding button to div elements in Javascript (Javascript)通过“document.createElement(”div“)”添加一些元素后重新初始化循环 - (Javascript) Re-Initialize Loop after adding some elements via "document.createElement("div")" 通过javascript中的DOM获取“必需的” div元素 - get "required' div elements via DOM in javascript 在javascript中向div标签添加新元素 - adding new elements to a div tag in javascript 使用JavaScript函数添加多个DIV元素 - Adding multiple DIV elements using functions with JavaScript 通过Javascript向Weebly添加元素不起作用 - Adding Elements to Weebly via Javascript Not Working 添加一个<div class></div>用 JavaScript 包围其他元素 - Adding a <div class></div> that encloses other elements with JavaScript 难以将唯一的事件侦听器添加到已创建的<div>通过 for 循环的元素</div><div id="text_translate"><p>我正在做一个项目来学习一些 JavaScript,目标是在单页 web 应用程序中动态提供电子邮件。 应用程序的HTML已经使用createElement JS方法创建。 到目前为止,我已经成功地显示了包含所有电子邮件的“收件箱”页面,如下图所示:</p><p> <a href="https://i.stack.imgur.com/V8cZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8cZq.png" alt=""></a></p><p> 我目前正在尝试通过使用 addEventListener 使这些单独的电子邮件中的每一个都可以点击。 我遇到的问题是,每当我单击任何一封电子邮件时,都会呈现收件箱中的第一个 email(id:1,主题:测试电子邮件),并且无法查看任何其他电子邮件。</p><p> <a href="https://i.stack.imgur.com/BBjQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBjQj.png" alt=""></a></p><p> 我可以看到相同的 email.id 被应用到所有创建的 div 的事件侦听器,尽管所有 div 都被正确创建,并包含来自相应电子邮件的所有信息。</p><p> 这是加载邮箱 JS,它呈现收件箱中的所有电子邮件:</p><pre> function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; // GET request fetch(`/emails/${mailbox}`).then(response => response.json()).then(emails => { // Print emails to console console.log(emails); // Iterate through each email for(var i = 0; i < emails.length; i++) { var email = emails[i]; // Create div and append email content to HTML var emaildiv = document.createElement('div'); emaildiv.style.borderStyle = 'solid'; emaildiv.style.borderColor = 'black'; emaildiv.style.borderWidth = '0.1rem'; emaildiv.style.borderRadius = '0'; emaildiv.style.marginBottom = '0.2rem'; emaildiv.style.padding = '0.3rem'; emaildiv.innerHTML = `<b>${email.sender}</b> --- ${email.subject}<br>${email.timestamp}`; // If individual email selected then view email emaildiv.addEventListener('click', () => view_email(email)); // Populate div HTML with emails document.querySelector('#emails-view').append(emaildiv); console.log(email.read); // Colour backgrounds based on whether emails have been read if (email.read == true) { emaildiv.style.backgroundColor = 'lightgrey'; } console.log(email); } });}</pre><p> 这是视图 email JS,它应该渲染个人 email 的 HTML:</p><pre> // View email function view_email(email) { console.log(email.id); // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'block'; // GET request fetch(`/emails/${email["id"]}`).then(response => response.json()).then(email => { // Create div, set class, and append email content to HTML var reademail = document.createElement('div'); reademail.innerHTML = ''; reademail.style.borderStyle = 'solid'; reademail.style.borderColor = 'black'; reademail.style.borderWidth = '0.1rem'; reademail.style.borderRadius = '0'; reademail.style.marginBottom = '0.2rem'; reademail.style.padding = '0.3rem'; reademail.innerHTML = ` <b>From:</b> ${email.sender}<br> <b>To:</b> ${email.recipients}<br> <b>Subject:</b> ${email.subject}<br> <b>Timestamp:</b> ${email.timestamp}<br> <button class="btn btn-sm btn-outline-primary" id="Reply">Reply</button> <hr> ${email.body}`; // Populate div HTML with emails document.querySelector('#single-view').append(reademail); // Mark unread emails as read if (email.read === 'false') { fetch(`/emails/${email}`, { method: 'PUT', body: JSON.stringify({ read: true }) }) } }); }</pre><p> 这是存储在 email GET 响应中的示例(虚拟数据):</p><pre> { "id": 1, "sender": "user@example.com", "recipients": ["user@example.com"], "subject": "Hello,": "body", "Hello, world:", "timestamp": "Oct 24 2020, 12:00 AM", "read": false, "archived": false }</pre><p> 我已经尝试将其他每封电子邮件的 ID 硬编码到视图 email JS 中,并且可以看到该功能按要求工作(显示电子邮件)。</p><p> 因此,我知道问题与上面的加载邮箱 JS 有关,并且可能与事件侦听器如何在 for 循环中应用有关。 如果有人可以阐明如何将唯一的事件侦听器应用于每个单独的 div,将不胜感激。</p><p> 谢谢!</p></div> - Difficulty adding unique event listener to created <div> elements via a for loop 通过JavaScript添加SVG剪切路径属性的问题 - Problems with adding SVG clip-path attribute via JavaScript 淡入和淡出 <div> 通过带有javascript和jquery的复选框的元素 - Fade in and out <div> elements via checkbox with javascript and jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM