I have a set of lists, and each block of the list has a data-id set. I hope to get the data-id of the clicked block when the block is clicked. However, I am not familiar with javascript yet, so I don’t know how to get it correctly. I hope you can help me, thank you.
let wrap = document.querySelector('.wrap');
let item = wrap.querySelectorAll('.notice_item');
for (let i = 0; i < item.length; i++) {
item[i].onclick = function(e) {
console.log(e.target.dataset.id)
}
}
.wrap {
display: flex;
flex-direction: column;
}
.wrap li {
padding: 16px;
}
.wrap li:hover {
background-color: yellow;
}
.wrap li .info_title {
font-size: 20px;
color: #222;
}
.wrap li .info_main {
font-size: 14px;
color: #222;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="wrap">
<li>
<a class="notice_item" href="javascript:;" data-id="111">
<div class="notice_content">
<h3 class="info_title">TITLE</h3>
<p class="info_main">Lorem ipsum dolor sit amet, consectetur adipisicing elit. In labore assumenda perspiciatis illum quo corrupti, magnam ratione fuga omnis enim!</p>
</div>
</a>
</li>
<li>
<a class="notice_item" href="javascript:;" data-id="222">
<div class="notice_content">
<h3 class="info_title">TITLE</h3>
<p class="info_main">Lorem ipsum dolor sit amet, consectetur adipisicing elit. In labore assumenda perspiciatis illum quo corrupti, magnam ratione fuga omnis enim!</p>
</div>
</a>
</li>
<li>
<a class="notice_item" href="javascript:;" data-id="333">
<div class="notice_content">
<h3 class="info_title">TITLE</h3>
<p class="info_main">Lorem ipsum dolor sit amet, consectetur adipisicing elit. In labore assumenda perspiciatis illum quo corrupti, magnam ratione fuga omnis enim!</p>
</div>
</a>
</li>
</ul>
4
Answers
I’ve modified a little your html removing the a tag.
i’ve add the listener to every div with class .notice_content ang get it’s data-id on click
This situation is better suited for the use of event delegation.
By the way, don’t use inline
javascript:
for hrefs (or inline handling for that matter).You were very close. Check the code below. hope this helps.
Here is the jQuery solution:
.data('id')
.find()
, such as.find('.info_title').text()
Note that often you do not need an ID in each list element because you can access what you need from the DOM. You can find a child element with
.find('.someClass')
, traverse one element up with.parent()
, find an element several levels up with.closest('.someClass')
.