使用纯JS单击时从li元素获取文本和ID [英] Get text and id from an li element on click with pure JS
问题描述
我已经坚持了好几天,但解决不了.
I've been stuck with this for several days and I can't solve it.
我已经用jQuery完成了它,但是我只需要纯JS.
I've done it with jQuery with no problem, but I need it in pure JS.
这是我的列表的生成方式.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
正如我所说,我要保存文本的值和所单击的任何li元素的ID.
As a said I want to save the value of the text and the id of any li element clicked.
致谢
推荐答案
您尚未指定这是针对特定列表还是页面上的任何li
.下面将记录页面上任何li
的id和innerHTML组件.也许您可能需要针对特定用例更新querySelector
.
you haven't specified whether this is for a specific list or just any li
on your page. The below will log the id and innerHTML components of any li
on the page. Perhaps you may need to update the querySelector
for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
这是一个 JSFiddle ,我认为它演示了您要实现的目标.
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
这篇关于使用纯JS单击时从li元素获取文本和ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!