问题描述
我的代码:
<script>
fetch('http://127.0.0.1:8000/chatbot/fetch/')
.then(response => response.json())
.then(function (data) {
console.log(data)
if (data.choices !== '') {
const htmlAnswer = data.answer.map(answer => {
return `
<button
class="max-w-sm py-3 px-4 focus:outline-none text-blue-500 hover:bg-blue-100 text-center transition ease-in-out duration-300">
??? ${answer}
</button>
`
}).join('')
document.getElementById('server-message').innerHTML = `
<div class="flex flex-col shadow rounded-lg my-3 max-w-sm border hover:border-indigo-300 hover:shadow-lg transition ease-in-out duration-300">
<div class="mb-0 py-3 px-4 max-w-sm bg-gray-200 rounded-lg rounded-b-none select-none">
${data.question}
</div>
${htmlAnswer}
</div>
`
}
document.addEventListener("DOMContentLoaded",function(){
document.getElementById("server-message").lastElementChild.classList.add('rounded-b-lg');
})
})
</script>
我想将类添加到父级的最后一个子级。我正在渲染JSON
中的父元素和子元素。我该如何运作?
在将这些元素呈现到HTML
之后,可能应该开始寻找子元素。我不知道该怎么做。
我在香草js中需要它。
解决方法
也许这会有所帮助。我检查了地图功能中的最后一项,并向其中添加了类
const answerLength = data.answer.length
const htmlAnswer = data.answer.map((answer,index)=> {
// if this is the last element then add the class
if(index+1 ==answerLength){
return `
<button
class="max-w-sm py-3 px-4 focus:outline-none text-blue-500 hover:bg-blue-100 text-center transition ease-in-out duration-300 rounded-b-lg">
??? ${answer}
</button>
`
}
else{
return `
<button
class="max-w-sm py-3 px-4 focus:outline-none text-blue-500 hover:bg-blue-100 text-center transition ease-in-out duration-300">
??? ${answer}
</button>
`
}
}).join('')