简体   繁体   中英

Selected List Item Color Change

I am creating a Web page that contains the following code.

<script>
function changeColor(c) {
document.getElementById("message").style.color=c;
}
</script>
<p id="message">Welcome!</p>
<ul id="color">
<li>Black</li>
<li>Red</li>
</ul>

I need to ensure that when I clicks an item in the list, the text color of the Welcome! message will change. Which declaration should you use?

<li onclick="changeColor(this.innnerHtml)"> Black </li>

New: JS Fiddle using the font color (not text) and JS to attach the event


JS Fiddle of the Below

<script>
   function changeColor(c) {
      document.getElementById("message").style.color=c;
   }
</script>

<p id="message">Welcome!</p>
<ul id="color">
   <li onclick="changeColor(this.innerHTML);">Black</li>
   <li onclick="changeColor(this.innerHTML);">Red</li>
</ul>

Note:

  1. This is not the best way to do this, especially if you have many list elements. A better way would be to use JavaScript; get the color unordered list, loop through each loop element, and add the changeColor(this.innerHTML) to the click event.

  2. innerText may be used instead of innerHTML

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