[英]How to target a specific element from a group of them having the same class/id in javascript?
I want to copy the text in the <li>
tag using JavaScript.我想使用 JavaScript 复制<li>
标签中的文本。 It should be copied when the <li>
tag is clicked.当点击<li>
标签时,它应该被复制。 All <li>
tags have the same class as they will get the same formatting through CSS.所有<li>
标签都具有相同的类,因为它们将通过 CSS 获得相同的格式。
As per my research, we need to specify the button a target class
which it will copy to clipboard(Using clipboard.js
).根据我的研究,我们需要为按钮指定一个目标class
,它将复制到剪贴板(使用clipboard.js
)。 The <li>
tag will be generated through js
so, to give different id
to each one of them will be difficult and will increase the code and reduce the speed too. <li>
标签将通过js
生成,因此为每个标签指定不同的id
会很困难,并且会增加代码并降低速度。
So how can copy the text of the li
tag that is being clicked through js/jquery/clipboard.js
etc.那么如何通过js/jquery/clipboard.js
等复制被点击的li
标签的文本呢?
<ul>
<li class="data">Lorem ipdolor.</li>
<li class="data">Lo ripsum dolor.</li>
<li class="data">Lorepsum dor.</li>
</ul>
There are different methods but two that stand up on top.有不同的方法,但有两种方法是最重要的。
$(function() { $("li[class='data']").click(function(e) { // 1) Use this reference console.log("1: " + $(this).text()); // 2) Use Event Target console.log("2: " + $(e.target).text()); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="data">Lorem ipdolor.</li> <li class="data">Lo ripsum dolor.</li> <li class="data">Lorepsum dor.</li> </ul>
You can put an id on ul:您可以在 ul 上放置一个 id:
<ul id="dataContainer">
<li class="data">sometext</li>
<li class="data">sometext1</li>
<li class="data">sometext2</li>
<li class="data">sometext3</li>
</ul>
Then:然后:
document.getElementById('dataContainer').addEventListener('click', function(e){
console.log(e.target.innerText);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.