简体   繁体   中英

How do I call alert window by click on list item element?

Could anyone please assist me with my simple script? I have a list of colors in html code and just need to make my js code to popup an alert with the clicked list item value. Please help me: Here is what I have:

HTML

<ul id="mylist">
  <li>White </li>
  <li>Silver </li>
  <li>Dark Gray</li>
  <li>Khaki </li>
</ul>

And here is JS code (it is displaying an alert with the list item value on window load but i need it to show up after clicking on each item)

<script language="JavaScript">
<!--
  var a = document.getElementById('mylist').document.getElementsByTagName('li');
  var b=[];
  for(i=0;i<a.length;i++)
  {
    b=a[i].innerText;
    alert(b);
  } 
//-->
</script>
document.getElementById('mylist').addEventListener('click', function(event) {
  if ('LI' != event.target.tagName) return;
  alert(event.target.innerText);
}, false);

See also:

var a = document.getElementById('mylist').getElementsByTagName('li');

for(var i = 0; i < a.length; i++){
      a[i].onclick = function(){
            alert(this.innerHTML);
      }
}

Demo: http://jsbin.com/ayefap/2/

 $(document).ready(function() { $("button").click(function() { $("li").each(function() { alert($(this).text()); }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>MILK</li> <li>CHOCOLATE</li> <li>BREAD</li> </ul> <button>Click to Alert</button>

var a = document.getElementById('mylist').getElementsByTagName('li');

document.getElementById("myList") doesn't have a .document

If you use firebug or chrome console you'll get this error there.

Without getting into hooking up click handlers in raw JavaScript, you can do this:

<li><a href="javascript://" onclick="alertMe(this)">White</a></li>

JS:

function alertMe(element) {
      alert(element.innerText)
}
<ul id="mylist">

    <li><a href="javascript:void(0)" onclick="clickMe(this)">White</a></li>
        <li>Silver </li>
            <li>Dark Gray</li>
                <li>Khaki </li>
</ul>

Add this to your head section:

<script type="text/javascript">
function clickMe(cid){
alert(cid.innerHTML);

}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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