创建收藏夹列表-如何在单击时将项目从一个列表复制到另一个列表



(Javascript新手(

我创建了一个输入框,它将输入值转换为列表项,并添加了一个星形

我正在尝试创建一个新的列表,当点击星星时,它将复制到的"收藏夹"部分

我试过这个,但它不起作用

let newStarSpan = document.querySelector("span")
newStarSpan.addEventListener('click', function(e){
//on click, get the parent node of the item clicked on 
//i.e., want to return the individual <li> list item for the starSpan that was cliked on
let favNode = this.parentNode 
//create a copy of this list item (the parent node)
let nodeCopy = favNode.cloneNode(true)
//add it to list B - favourites list 
listB.appendChild(nodeCopy)

https://codepen.io/jemimacholzer/pen/dyYMKxj

您的代码中很少有问题,第一个问题与选择器有关

const listB = document.querySelector('listB')

用更新

Fix:
const listB = document.getElementById('listB')

另一个问题与CCD_ 1事件声明&在btn.onclick函数之外,不能访问newSpan

您还为newSpan分配了click listener,它似乎声明&当Dom中不存在newSpan时,在页面上绑定。因此,您不需要定义侦听器,而是需要创建一个函数,该函数在newSpan上触发,并在创建newSpan期间单击并绑定该函数。

const listA = document.getElementById("listA")
const input = document.querySelector('input')
const btn = document.querySelector('button')
const listB = document.getElementById('listB')
btn.onclick = function() {
let Shopitem = input.value //store current value of input element in variable 
input.value = ' ' //empty input element 
const listItem = document.createElement('li') //creating a list item for the shopping item 
listItem.setAttribute('id', Shopitem)
const span = document.createElement('span') //list text 
const newBtn = document.createElement('button') //creating button to delete item 
var starSpan = document.createElement("span")
var text = document.createTextNode("u2B50")
starSpan.appendChild(text)
//making span and button children of the list item (containing within each list item)
listItem.appendChild(starSpan)
listItem.appendChild(span)  //add list text to list item 
listItem.appendChild(newBtn) //add list remove button to list item 
newBtn.textContent = 'Delete'
span.textContent = Shopitem 
listA.appendChild(listItem) //add li to the ul list 
newBtn.onclick = function(e) {
list.removeChild(listItem)
}
starSpan.onclick = function(e) {
cloneListItem(listItem)
}
input.focus(); //focus the input method ready for entering the next shopping list item 
}
//need to create new reference to star span as old reference is inside eother function
function cloneListItem(favNode){
//create a copy of this list item (the parent node)
let nodeCopy = favNode.cloneNode(true)
//add it to list B - favourites list 
listB.appendChild(nodeCopy)
}

https://codepen.io/jemimacholzer/pen/dyYMKxj

最新更新