البرمجة

تغيير لون خلفية عناصر القائمة في JavaScript

To fix the issue with changing the background color of your list elements, you need to correct the function call in your HTML and use the correct method to get elements by class name. Here’s the corrected code:

javascript
change(num, element){ var text; if (num == 1){ text = "First"; } else if (num == 2) { text = "Second"; } else { text = "Third"; } document.getElementById('text').innerHTML = text; // Use getElementsByClassName to select elements with a specific class var elements = document.getElementsByClassName("left"); for (var i = 0; i < elements.length; i++) { elements[i].style.backgroundColor = "black"; } // Change the background color of the clicked element to white element.style.backgroundColor = "white"; }

And your corrected HTML:

html
<ul> <li><a class="left" href="#" onclick="change(1,this)">Firsta>li> <li><a class="left" href="#" onclick="change(2,this)">Seconda>li> <li><a class="left" href="#" onclick="change(3,this)">Thirda>li> ul>

In this code, the getElementsByClassName method is used to select all elements with the class name “left”, and then a loop is used to change the background color of all these elements to black. After that, the background color of the clicked element is changed to white.

المزيد من المعلومات

لتوضيح المزيد من المعلومات، يمكن توضيح بعض النقاط الهامة في الكود:

  1. في الدالة change، تقوم بتعيين قيمة لمتغير text استنادًا إلى القيمة التي تم تمريرها للدالة. على سبيل المثال، إذا كانت القيمة num تساوي 1، يتم تعيين قيمة “First” لمتغير text.

  2. بعد ذلك، يتم تحديث محتوى العنصر الذي يحمل id “text” في صفحتك بقيمة المتغير text، والتي تم تحديدها في الخطوة السابقة.

  3. يتم استخدام الدالة getElementsByClassName لاختيار جميع العناصر التي تحمل الفئة “left”، ومن ثم يتم تكرارها في حلقة for لتغيير لون خلفيتها إلى اللون الأسود.

  4. أخيرًا، يتم تغيير لون خلفية العنصر الذي تم النقر عليه (element) إلى اللون الأبيض.

باستخدام هذه الإصلاحات، يجب أن تعمل الآن وظيفة تغيير لون خلفية عناصر القائمة بناءً على العنصر المحدد.

زر الذهاب إلى الأعلى