I want to click on each item to capture the value of the data-id attribute inside, but I did some research on the Internet! I still encounter many difficulties, and I still can’t figure out how to capture the data-id in each item The value, I hope someone can give me guidance~ I feel that I am in the process of learning the program, and I feel a lot of frustration
document.addEventListener("click", handle);
const demo = e.target.closest(".demo");
let item = document.querySelectorAll(".item");
for (let i = 0; i < item.length; i++) {
item[i].onclick = function(e) {
console.log(e.target.dataset.id)
};
}
body {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.demo {
display: inline-block;
border: 1px solid #222;
}
.item {
border: 1px solid #222;
padding: 30px;
}
.item:hover {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="demo">
<li class="item" data-id="11111">
<span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Esse, mollitia! Aspernatur animi similique temporibus quidem ullam officiis distinctio deleniti alias.</span>
</li>
<li class="item" data-id="22222">
<span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Esse, mollitia! Aspernatur animi similique temporibus quidem ullam officiis distinctio deleniti alias.</span>
</li>
<li class="item" data-id="333">
<span>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Esse, mollitia! Aspernatur animi similique temporibus quidem ullam officiis distinctio deleniti alias.</span>
</li>
</ul>
2
Answers
Don’t mix native JavaScript and jQuery, better use one or the other. Here is a jQuery solution:
You have a
span
element wrapping everything in theli
thespan
is the actual event target.Use the
this
keyword instead which references the element the event listener is attached to.