Javascript 如何在js的新标题中的新div中创建新img?
我想在js中创建滑块。这是我的密码。问题是我如何提到,在新的Javascript 如何在js的新标题中的新div中创建新img?,javascript,html,Javascript,Html,我想在js中创建滑块。这是我的密码。问题是我如何提到,在新的div元素中创建新的img元素在新的header元素中“同时”,类似于header>div>img const myRequest = new Request('./database.json'); const myHeader = document.querySelector('main'); export const headerTwo = (fragment) => { fetch(myRequest) .
div
元素中创建新的img
元素在新的header
元素中“同时”,类似于header>div>img
const myRequest = new Request('./database.json');
const myHeader = document.querySelector('main');
export const headerTwo = (fragment) => {
fetch(myRequest)
.then(function (response) {
console.warn(response);
return response.json();
})
.then(function () {
let header = document.createElement('div');
// above is the problem with creating header > div > img
header.setAttribute('class', 'slider');
const slideList = [{
img: "https://",
text: 'sth 1'},{
img: "https://",
text: 'sth 2'},{
img: "https://",
text: 'sth 3'}
];
const time = 3000;
let active = 0;
const changeSlide = () => {
active++;
if (active === slideList.length) {
active = 0;
}
header.src = slideList[active].img;
header.textContent = slideList[active].text;
};
let indexInterval = setInterval(changeSlide, time);
myHeader.appendChild(header);
})
.then(function() {
console.log('Co to ????');
})
.catch(function (error) {
console.log('--------- ', error);
});
}
该代码应该可以做到这一点
let header = document.createElement('header')
let div = document.createElement('div')
let img = document.createElement('img')
img.setAttribute('src','') // set value
div.appendChild(img)
header.appendChild(div)
然后在需要的地方附加标题您不能在
div
标记上设置src
属性-它不会做任何事情。看起来您正期待着从中神奇地创建并附加一个图像。我认为jQuery可以提供帮助。我是这样使用的:$('.slider').wrapAll('');我知道jQuery有点过时;-)