简体   繁体   English

您如何提醒内部 html 没有 id 的点击 div?

[英]How can you alert the inner html of a clicked div with no id?

In an instance where you are trying to get multiple divs with different contents to alert their contents on click It might be common for them to each have the same class and no unique ids.在您尝试获取具有不同内容的多个 div 以在单击时提醒它们的内容的情况下,它们每个都具有相同的 class 并且没有唯一 ID 可能很常见。 How can I alert the inner html of a div when clicked if it is only identified by a class name?如果仅由 class 名称标识,单击时如何提醒 div 的内部 html? : For example: : 例如:

html html

<div class='button'> a </div>
<div class='button'> b </div>
<div class='button'> c </div> 
<div class='button'> d </div> 
document.querySelectorAll('.button').forEach(item => {
  item.addEventListener('click', event => {
    alert(this.innerHTML)
  })
})

use event.target to get access to the very element you have just clicked:使用event.target访问您刚刚单击的元素:

document.querySelectorAll('.button').forEach(item => {
item.addEventListener('click', event => {alert(event.target.innerHTML)
})
})

From this reference , the target property of Event interface will refence the object onto which the event was dispatched.从这个 引用中, Event接口的target属性将引用事件被调度到的 object。

So you can get the text inside the clicked div using event.target .因此,您可以使用event.target获取单击的div内的文本。

 document.querySelectorAll('.button').forEach(item => { item.addEventListener('click', (event) => { alert(event.target.innerHTML); }); });
 <div class='button'> a </div> <div class='button'> b </div> <div class='button'> c </div> <div class='button'> d </div>

In your case just replacing this with item would make your snippet work:在您的情况下,只需将this替换为item即可使您的代码段起作用:

 document.querySelectorAll('.button').forEach(item => { item.addEventListener('click', event => { alert(item.innerHTML) }) })
 <div class='button'> a </div> <div class='button'> b </div> <div class='button'> c </div> <div class='button'> d </div>

Word of advice: if you are adding interactivity, use "real" button elements that are designed for it: you'll get keyboard support and better accessibility overall for free.忠告:如果您要添加交互性,请使用专为它设计的“真实” button元素:您将免费获得键盘支持和更好的整体可访问性。

Also, you can use single handler attached at some parents of target elements, what is said to be better in certain scenarios:此外,您可以使用附加在目标元素的某些父级的单个处理程序,据说在某些情况下更好:

 document.body.addEventListener('click',buttonClick); function buttonClick(event){ var tgt = event.target; if(tgt.tagName;= 'BUTTON') return. alert( "»" + tgt;innerText + "«"); }
 button { display: block; }
 <button> a </button> <button> b </button> <button> c </button> <button> d </button>

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

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