简体   繁体   English

用纯javascript获取li框的第一个标签textcontent

[英]Get first tag textcontent of li box with pure javascript

I want to have the first tag of (name) of my li whenever the li box is being clicked.每当单击 li 框时,我都希望拥有我的 li 的(名称)的第一个标签。 But currently my code will only display the tag that is clicked.但目前我的代码只会显示被点击的标签。

Here is link to jsfiddle https://jsfiddle.net/ehagk1d7/ because the exact same code doesn't seem to work in snippet.这是 jsfiddle https://jsfiddle.net/ehagk1d7/的链接,因为完全相同的代码似乎在片段中不起作用。

 function test() { console.log(event.target.textContent); }
 <li class="lijst" onclick="test()"> <p>Naam, PraktijkNaam</p> <p>Adres</p> <p>Email</p> <p>Mobiel</p> </li>

You can use this as a parameter to add the element the handler is attached to.您可以使用this作为参数来添加处理程序附加到的元素。 You can then use this parameter in the handler function.然后,您可以在处理程序 function 中使用此参数。 event.target will refer to the clicked element which propagates to the lijst element, not the element the handler is attached to. event.target将引用传播到lijst元素的单击元素,而不是处理程序附加到的元素。 querySelector() will return the first matched element. querySelector()将返回第一个匹配的元素。

 function test(el) { console.log(el.querySelector('p').textContent); }
 <li class="lijst" onclick="test(this)"> <p>Naam, PraktijkNaam</p> <p>Adres</p> <p>Email</p> <p>Mobiel</p> </li>

Better would be to get rid of the inline event handler and define the event handler in javascript as in snippet below.最好摆脱内联事件处理程序并在 javascript 中定义事件处理程序,如下面的片段所示。

 document.querySelectorAll('.lijst').forEach(el => { el.addEventListener('click', function(){ console.log(this.querySelector('p').textContent); }); });
 <li class="lijst"> <p>Naam, PraktijkNaam</p> <p>Adres</p> <p>Email</p> <p>Mobiel</p> </li> <li class="lijst"> <p>Naam, Nog een PraktijkNaam</p> <p>Adres</p> <p>Email</p> <p>Mobiel</p> </li>

use firstElementChild使用firstElementChild

 function test(el) { alert(el.firstElementChild.textContent ); }
 <li class="lijst" onclick="test(this)"> <p>Naam, PraktijkNaam</p> <p>Adres</p> <p>Email</p> <p>Mobiel</p> </li>

If you want to stay with event element use currentTarget which is always the origin "node" of your function如果您想保留事件元素,请使用currentTarget ,它始终是您的 function 的原点“节点”

 function test() { console.log(event.currentTarget.firstElementChild.textContent); }
 <li class="lijst" onclick="test()"> <p>Naam, PraktijkNaam</p> <p>Adres</p> <p>Email</p> <p>Mobiel</p> </li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM