如何使用JavaScript动态创建HTML标签(包含内容)?

时间:2019-06-21 19:17:40

标签: javascript html children

我正在尝试将此HTML代码转换为由Javascript即时生成的实时数据。

<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

我发现了一些方法,例如:appendChild,getElementById,innerHTML等。到目前为止,这是我尝试过的。我似乎无法显示数据。

                               stringy = data2.Items[0].groupName.values[i];
                               var para = document.createElement("div");
                               var node = document.createTextNode(stringy);
                               para.appendChild(node);
                               var element = document.getElementById("parental");
                               element.appendChild(para);

                               //create div and give it a class
                                para.setAttribute('class', 'dropbtn');
                                var div = document.createElement("div");
                                div.setAttribute('class', 'dropdown-content');
                                para.parentNode.insertBefore(div, para.nextSibling);
                    //create link tags and give them text
                                var alinky = document.createElement("a");
                                alinky.setAttribute('id', 'linky');
                                document.getElementById('linky').innerHTML = "linky poo"
                                div.appendChild(alinky);

希望有人可以填写空白内容,以使此HTML代码可以用javascript复制。预先感谢!

编辑:

我正在尝试创建一个像这样的下拉菜单: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_hover

但是,我试图创建多个下拉菜单,这些菜单根据对DynamoDB(AWS)的查询来动态更改数量。因此,我正在使用javascript创建html标签。

问题在于查询功能的范围不允许我查看查询功能之外的数据,甚至无法将数据注入其中。

例如,如果我尝试从查询中获取按钮描述,并将其写入descriptionArray[0] = data2.Items[0].description;,以便可以将按钮附加到下拉div,则它不知道我正在进行的迭代由于范围而在for循环中。在此示例中,descriptionArray[0]将起作用,但descriptionArray[i]将不起作用,因为for循环在查询之外。

这是整个逻辑:

                        //group data   
                        var length =  data2.Items[0].groupName.values.length;
                        // create elements
                        const dpdown1 = document.createElement('div');
                        // set dpdown1 class
                        dpdown1.setAttribute('class', 'dropdown');
                        console.log(dpdown1); 

                        var button = new Array();
                        var dpdown2 = new Array();   
                        var membersArray = new Array();
                        var descriptionArray = new Array(); 
                        var linksArray = new Array();
                        var stringy = new Array; 

                            //list groups
                            for(i = 0; i<length; i++){
                                // create button, set button attribs
                                button[i] = document.createElement('button');
                                button[i].setAttribute('class','dropbtn');
                                //create dropdown div, set attributes
                                dpdown2[i] = document.createElement('div');
                                dpdown2[i].setAttribute('class', 'dropdown-content');

                                //list of group names
                                stringy[i] = data2.Items[0].groupName.values[i];
                                var stringyy = stringy[i];
                                var desc;
                                //query group members and description                        
                                var docClient1 = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
                                var identityId = AWS.config.credentials.identityId;
                                var paramsyy = {
                                    ExpressionAttributeValues: {
                                        ":v1": stringyy
                                    },
                                    KeyConditionExpression: "groupName = :v1",
                                    TableName: "group"
                                };
                                docClient1.query(paramsyy, function(err, data2) {
                                    if (err) {
                                        console.error(err);
                                    }else{

                                        descriptionArray[0] = data2.Items[0].description;
                                        //traverse members
                                        for(k = 0; k<data2.Items[0].members.values.length; k++){
                                          // create dropdown links of members
                                          membersArray[k] = data2.Items[0].members.values[k];
                                          linksArray[k] = document.createElement('a');
                                          linksArray[k].setAttribute('href', '#')
                                          linksArray[k].innerText = membersArray[k];

                                          // nest into dpdown2 div, set dpdown2 attribs
                                          dpdown2[0].appendChild(linksArray[k]);

                                        }     
                                    }          
                                });

                                button[i].innerText = stringyy + ": " + descriptionArray[0];

                                // nest into dpdown1
                                dpdown1.appendChild(button[i]);
                                dpdown1.appendChild(dpdown2[i]);
                            }
                            // append to DOM
                            const target = document.getElementById('target');
                            target.appendChild(dpdown1);

如果我在查询函数中使用第一个for循环中的I,它将给我未定义的结果。

2 个答案:

答案 0 :(得分:1)

这是使用香草JavaScipt的方法,有多种方法,但是这种方法仅使用4种方法:createElementsetAttributeappendChild和{{ 1}},并直接设置1个属性:getElementById

innerText
// create elements
const dpdown1 = document.createElement('div');
const button = document.createElement('button');
const dpdown2 = document.createElement('div');
const link1 = document.createElement('a');
const link2 = document.createElement('a');
const link3 = document.createElement('a');

// set link attribs
link1.setAttribute('href', '#')
link1.innerText = 'Link 1';
link2.setAttribute('href', '#')
link2.innerText = 'Link 2';
link3.setAttribute('href', '#')
link3.innerText = 'Link 3';

// nest into dpdown2, set dpdown2 attribs
dpdown2.appendChild(link1);
dpdown2.appendChild(link2);
dpdown2.appendChild(link3);
dpdown2.setAttribute('class', 'dropdown-content');

// set button attribs
button.setAttribute('class','dropbtn');
button.innerText = "Dropdown"

// nest into dpdown1
dpdown1.appendChild(button);
dpdown1.appendChild(dpdown2);

// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');

// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);

您将把它附加到某个内容上,在本例中为<div id="target"></div>,但也可能是其他内容。

编码愉快!

答案 1 :(得分:1)

主要是您只是在做混乱的事情。

  1. 使用其类创建.dropdown <div>
  2. 用其类别和文本填写.dropbtn <button>
  3. 将按钮添加到div。
  4. 创建.dropdown-content <div>
  5. 通过每个链接的href属性和文字来完成。
  6. 将每个链接添加到.dropdown-content <div>
  7. .dropdown-content div添加到.dropdown <div>
  8. 在文档中找到父元素。
  9. 将完整的.dropdown <div>附加到文档中。

var para = document.createElement("div"); //make .dropdown div
para.setAttribute('class', 'dropdown'); //add .dropdown class to div
var button = document.createElement("button"); //create button
button.setAttribute('class', 'dropbtn'); //add .dropbtn class to button
var node = document.createTextNode('Dropdown'); //create button text
button.appendChild(node); //add text to button
para.appendChild(button); //add button to .dropdown div

var div = document.createElement("div"); //create .dropdown-content div
div.setAttribute('class', 'dropdown-content'); //add .dropdown-content class to div

//repeat for all necessary links
var alinky = document.createElement("a"); //creat link
alinky.setAttribute('href', '#'); //set link href attribute
var alinkyText = document.createTextNode("Link 1"); //create text for link
alinky.appendChild(alinkyText); //add text to link
div.appendChild(alinky); //add link to dropdown div

para.appendChild(div); //add .dropdown-content div to .dropdown div

var element = document.getElementById("parental"); //find parent element
element.parentNode.insertBefore(para, element.nextSibling); //add .dropdown div to the bottom of the parent element
<div id="parental">

</div>