[英]I want to combine 2 array with Javascript
This is HTML of two array.这是两个数组的 HTML。 I need to click ul.left and ul.right.
我需要点击 ul.left 和 ul.right。 (example- 1&a, 1&c, 2&b ...) When I click the left array and the right array, I need to get the left/right combination in the div.input.
(示例- 1&a, 1&c, 2&b ...) 当我单击左数组和右数组时,我需要在 div.input 中获取左/右组合。
<ul class="left">
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
<ul class="right">
<li><button>a</button></li>
<li><button>b</button></li>
<li><button>c</button></li>
</ul>
<div class="input"> </div>
Javascript: Javascript:
const arrayRight = document.querySelectorAll('.right li');
const arrayLeft = document.querySelectorAll('.left li');
const input = document.getElementsByClassName('input');
Array.from(arrayRight).addEventListener('click', el => {
Array.from(arrayLeft).addEventListener('click', ele => {
input.appendChild(span);
span.textContent = '${ele.innerText} / ${el.innerText}';
});
});
This is how you can do it.这就是你可以做到的。 document.querySelectorAll returns a node list, if you want to add event listeners, you need to loop through that nodelist using forEach or a similar loop (for...of, classic for etc.)
document.querySelectorAll 返回一个节点列表,如果要添加事件侦听器,则需要使用 forEach 或类似循环(for...of、classic for 等)遍历该节点列表
const arrayRight = document.querySelectorAll('.right li'); const arrayLeft = document.querySelectorAll('.left li'); const input = document.querySelector('.input'); arrayLeft.forEach((element, index) => { element.addEventListener('click', () => { input.innerHTML = `<span>${element.textContent} / ${arrayRight[index].textContent}</span>`; }); }); arrayRight.forEach((element, index) => { element.addEventListener('click', () => { input.innerHTML = `<span>${arrayLeft[index].textContent} / ${element.textContent} </span>`; }); });
<ul class="left"> <li><button>1</button></li> <li><button>2</button></li> <li><button>3</button></li> </ul> <ul class="right"> <li><button>a</button></li> <li><button>b</button></li> <li><button>c</button></li> </ul> <div class="input"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.