gpt4 book ai didi

javascript - 如何在此 JS 结构中仅向第一个 DIV 添加新类

转载 作者:行者123 更新时间:2023-12-02 19:04:05 27 4
gpt4 key购买 nike

当我从这个文本框中添加一些行时,我有这个文本框,然后这些行添加到类似这样的结构中。

您可以通过复制/粘贴检查此行并将其插入到此文本框:

问题1:天空的颜色是...?

问题 2:纸张来自...?

问题 3:一天有多少小时?

问题4:长颈鹿是鱼吗?

enter image description here

但现在我的需要是我想在第一行添加一个额外的类 answer,如下所示:

enter image description here

我的所有 JS 文本框代码是:

const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;

sendButton.addEventListener('click', function() {
// split the textarea entries into an array
let lines = (textArea.value).split("\n");

// iterate over each line, creating a div/span and inserting into the DOM
lines.forEach( (line) => {
let encodedLine = encodeHtmlEntity(line);
let newElement = `<div class="quiz">${encodedLine}</div>`;

innerDiv.innerHTML += newElement;
});

// reset the textarea
textArea.value = '';

});

function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});

return output;
}
<div id="inner"> </div>


<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">add text</button>

我怎样才能做到这一点。请解决我的问题。我需要编写哪些额外的代码行?

提前致谢,爱你。

最佳答案

如果您确定总是存在,至少有一个“测验”类元素:

document.getElementsByClassName('quiz')[0].classList.add('answer')

[0] 表示具有“quiz”类的第一个元素。


注意:如果根本没有“quiz”类元素,则:

document.getElementsByClassName('quiz')[0] === undefined

将是 true 并且该行将抛出如下错误:

Cannot read property 'classList' of undefined

关于javascript - 如何在此 JS 结构中仅向第一个 DIV 添加新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65307758/

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