如何解决将数组传递给函数,但记录为未定义
我有2个事件侦听器,它们都将被单击的元素推送到2个单独的数组中。事件侦听器中的这些console.log功能符合预期,但是当我将它们传递给move
函数时,它们都返回未定义。
我已经尝试过将选择的元素也传递到函数中,并且结果相同。
document.querySelectorAll('img').forEach(function(el) {
el.addEventListener('click',function(params) {
el.classList.add('selected')
selectedPieces.push(el)
console.log(selectedPieces)
moveBy(selectedPieces)
})
})
document.querySelectorAll('.square').forEach(function(el) {
el.addEventListener('click',function() {
el.classList.add('target')
targetPieces.push(el)
console.log(targetPieces)
moveBy(targetPieces)
})
})
function moveBy(selected,target) {
console.log(selected)
console.log(target)
}
解决方法
所以我确实为此做了一个工作。它涉及到将addEventListeners发送到它们自己的函数,然后将它们添加到数组中,然后将该数组发送到它自己的函数中,然后允许我四处移动。
此版本唯一的问题是它只能运行一次,所以我目前正在研究导致它仅启动一次的原因。
document.querySelectorAll('img').forEach(function(el) {
el.addEventListener('click',addselected)
})
document.querySelectorAll('.square').forEach(function(el) {
el.addEventListener('click',addtarget)
})
function addselected(selected){
console.log('---addselected---')
var select = selected.path[0]
moveList.push(select)
}
function addtarget(target){
console.log('---addtarget---')
if (target.path.length === 7){
var tar = target.path[1]
}else{
var tar = target.path[0]
}
moveList.push(tar)
moveBy(...moveList)
}
function moveBy(...moveList) {
console.log('---moveBy---')
let moveTarg = moveList[2]
let moveSel = moveList[0]
if (typeof moveTarg === 'undefined') {
console.log('not working')
}else{
moveTarg.appendChild(moveSel)
moveList = []
}
console.log(moveList)
}
,
好吧
function moveBy(selected,target) {
console.log(selected)
console.log(target)
}
有两个参数。
moveBy(targetPieces)
但是您只能传入一个参数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。