如何使用JavaScript动态创建指定结构样式的div元素?
问题解答
你原有的CSS代码无需修改,正常引入页面即可生效。
一、动态生成DOM的两种实现方案
你可以二选一,两种都满足「仅函数执行时才创建元素」的需求:
方案1:直接拼接HTML字符串插入
适合结构复杂的场景,代码编写效率更高。注意如果插入的内容包含用户提交的不可信内容,需要做XSS转义,你当前的业务场景都是自身输出的学生信息,可直接使用。
因为你原有结构包含PHP输出的变量,需要先把PHP变量注入到JS上下文中,示例代码如下:
// 先把PHP变量输出到JS变量(这行代码要写在PHP能解析的页面里,比如.php后缀的文件) const studentInfo = { id: <?php echo $studentid ?>, firstName: '<?php echo $firstname ?>', lastName: '<?php echo $lastname ?>', ako: '<?php echo $ako ?>' } // 生成元素的函数 function createStudentRow() { // 找到你要插入的父容器,比如页面里的某个列表容器,这里假设父容器id是studentList const parent = document.querySelector('#studentList') // 拼接HTML字符串 const rowHtml = ` <div class='rowcontainer' id="r${studentInfo.id}"> <div class='name'><t>${studentInfo.firstName} ${studentInfo.lastName}</t></div> <div class='ako'><t>${studentInfo.ako}</t></div> <div class='select'> <input type='checkbox' class='checkbox move'> </div> </div> ` // 插入到父容器末尾,你也可以根据需求用insertBefore等方法调整插入位置 parent.insertAdjacentHTML('beforeend', rowHtml) }
需要用的时候直接调用createStudentRow()即可。
方案2:使用原生DOM API创建
安全性更高,不会触发父容器的整体重解析,性能更优,示例代码如下:
const studentInfo = { id: <?php echo $studentid ?>, firstName: '<?php echo $firstname ?>', lastName: '<?php echo $lastname ?>', ako: '<?php echo $ako ?>' } function createStudentRow() { const parent = document.querySelector('#studentList') // 创建外层容器 const rowContainer = document.createElement('div') rowContainer.className = 'rowcontainer' rowContainer.id = `r${studentInfo.id}` // 创建name节点 const nameDiv = document.createElement('div') nameDiv.className = 'name' const t1 = document.createElement('t') t1.textContent = `${studentInfo.firstName} ${studentInfo.lastName}` nameDiv.appendChild(t1) rowContainer.appendChild(nameDiv) // 创建ako节点 const akoDiv = document.createElement('div') akoDiv.className = 'ako' const t2 = document.createElement('t') t2.textContent = studentInfo.ako akoDiv.appendChild(t2) rowContainer.appendChild(akoDiv) // 创建select节点 const selectDiv = document.createElement('div') selectDiv.className = 'select' const checkbox = document.createElement('input') checkbox.type = 'checkbox' checkbox.className = 'checkbox move' selectDiv.appendChild(checkbox) rowContainer.appendChild(selectDiv) // 插入到父容器 parent.appendChild(rowContainer) }
二、你的测试代码错误修正
你写的测试代码存在3个错误,所以无法渲染:
- 错误1:
appendChild方法需要传入DOM对象,你传入了字符串"div",应该传入你创建的变量div - 错误2:不能直接向
document对象插入子元素,需要插入到document.body或者你指定的容器节点下 - 错误3:
div.style是CSSStyleDeclaration对象,不能直接赋值字符串,需要用cssText属性赋值整段样式,或者单独给每个样式属性赋值
修正后的代码如下:
<body> <script> let div = document.createElement("div"); div.id = "div_id" ; div.className = "div_class"; // 用cssText赋值整段样式,或者分开写div.style.backgroundColor = 'red' div.style.cssText = "background-color: red;"; div.style.width = "100px"; div.style.height = "100px"; // 插入到body下 document.body.appendChild(div); </script> </body>
内容的提问来源于stack exchange,提问作者Sam Holland
相关产品推荐
相关产品推荐

