Javascript:我如何显示我点击的这些元素?



我必须采用点击的数据过滤器属性,因为这些是<ul>列表的唯一区别,我不能改变它们的内部HTML。

现在它只能使用"Phone",但我想要"Phone"当我点击例如"平板"时消失。

var outputText = "";
const conbtn = document.querySelectorAll('li[data-filter=".eael-cf-phone"]', 'li[data-filter=".eael-cf-tablet"]', 'li[data-filter=".eael-cf-Laptop"]', 'li[data-filter=".eael-cf-PC"]');
var output = document.getElementById('output');
for (var i = 0; i < conbtn.length; i++) {
outputText += conbtn[i].innerText;
};
conbtn.forEach(function(elem) {
elem.addEventListener("click", function() {
document.getElementById('output').innerText = outputText;
});
});
<div class="container">
<div class="row">
<div class="col-6">
<ul>
<li data-load-more-status="0" data-first-init="1" class="control all-control" data-filter="*">All</li>
<li data-load-more-status="0" data-first-init="0" class="control" data-filter=".eael-cf-phone">Phone</li>
<li data-load-more-status="0" data-first-init="0" class="control active" data-filter=".eael-cf-tablet">Tablet</li>
<li data-load-more-status="0" data-first-init="0" class="control" data-filter=".eael-cf-laptop">Laptop</li>
<li data-load-more-status="0" data-first-init="0" class="control" data-filter=".eael-cf-pc">PC</li>
</ul>
</div>
<div class="col-6">
<p id="output" style="text-align:center;font-size: 20px;">Output:
</p>
</div>
</div>
</div>

https://jsfiddle.net/8debzkh3/

这是你想要的吗?每次点击都会显示所点击项目的内容。

const conbtn = document.querySelectorAll('li[data-filter]');
const output = document.getElementById('output');
conbtn.forEach(function(elem) {
elem.addEventListener("click", function(e) {
output.innerText = e.target.innerText;
});
}); 

你可以尝试这样做:

var outputText = "";
// XYZ would be replaced with a better class name
const conbtn = document.querySelectorAll('.xyz .control');
var output = document.getElementById('output');
conbtn.forEach(function(elem) {
elem.addEventListener("click", function() {
output.innerText = elem.innerText;
});
});
<div class="container">
<div class="row">
<div class="col-6">
<ul class="xyz">
<li data-load-more-status="0" data-first-init="1" class="control all-control" data-filter="*">All</li>
<li data-load-more-status="0" data-first-init="0" class="control">Phone</li>
<li data-load-more-status="0" data-first-init="0" class="control active">Tablet</li>
<li data-load-more-status="0" data-first-init="0" class="control">Laptop</li>
<li data-load-more-status="0" data-first-init="0" class="control">PC</li>
</ul>
</div>
<div class="col-6">
<p id="output" style="text-align:center;font-size: 20px;">Output:
</p>
</div>
</div>
</div>

我将定义一个函数,该函数接受一个事件,并将输出元素的内部文本更新为事件目标的内部文本:

const conbtn = document.querySelectorAll('li[data-filter]');
const output = document.getElementById('output');
function updateOutput(e) {
output.innerText = e.target.innerText;
}
conbtn.forEach(elem => elem.addEventListener("click", updateOutput)); 

相关内容

  • 没有找到相关文章

最新更新