gpt4 book ai didi

javascript - 使用 CSS 添加一个 div 到 DOM

转载 作者:行者123 更新时间:2023-11-28 16:58:04 25 4
gpt4 key购买 nike

对于一个元素,我正在构建一个获取用户输入、将其存储在数组中并在 DOM 中显示输入的应用。我做了前两部分,但我无法显示它。更具体地说,我无法显示 CSS。

我试过 .createElement() 创建一个新的列表项,但它不包含 CSS。我开始认为我完全错误地解决了这个问题。如果您需要更多信息或代码,请告诉我。

\\HTML

<div id="boxhold">
<ul>
<li>
<div class="twogrid">
<h1>Fruit Juice</h1>
<p>50</p>
</div>
</li>
</ul>
</div>

\\CSS

#boxhold {
margin: 0 auto;
ul {
list-style-type: none;
padding: 0;
li {
margin: 0 auto;
width: 408px;
height: 75px;
border: 3px solid $prime-color;
h1 {
font-family: $header-font;
font-weight: $header-weight;
font-size: 1em;
}
p {
font-family: $header-font;
font-weight: $header-weight;
}
}
}
}

\\JS
//Get Data

//Empty array for storing
var added = [];

//Get Data
var userInput = function() {
return {
name: document.getElementById('name').value,
amount: document.getElementById('amount').value
}
};


// Store Data
var newSugar = function(){
return added.push(userInput());
}

// New HTML
function newBox() {
var newLi = document.createElement('li');

var newName = document.getElementById('name').value;
var n = document.createTextNode(newName);
newLi.appendChild(n);

var newAmount = document.getElementById('amount').value;
var a = document.createTextNode(newAmount);
newLi.appendChild(a);

var boxhold = document.getElementById('boxhold').getElementsByTagName('ul')[0];

document.body.appendChild(newLi);
};

//Adding stuff

var displayData = (function() {

var addInput = function() {
var data = userInput();
var item = newSugar();
var box = newBox();
//var box = newItem();
};


var addFood = document.getElementById('addFood');
addFood.addEventListener('click', addInput);

document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
addInput();
}
});
})(userInput, newSugar, newBox);

最佳答案

欢迎来到 Stack Overflow @nzart 👋

看起来您正在将新创建的列表项附加到文档的正文中,这意味着它将作为页面的最后一个元素添加。您的 CSS 指示样式仅适用于无序列表中的列表项,因此这可以解释缺少样式的原因。

简单的修复应该是将 document.body.appendChild(newLi); 替换为 boxhold.appendChild(newLi);。希望对您有所帮助!

关于javascript - 使用 CSS 添加一个 div 到 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com