البرمجة
حل مشكلة إضافة كلاس إلى عنصر معين باستخدام jQuery
06/03/2024آخر تحديث: 06/03/2024
3 دقيقة واحدة
The issue you’re facing is likely due to the selector $('h3')
targeting all
elements on the page, not just the one you’re interested in. To target only the specific
مقالات ذات صلة
element you want, you can use jQuery’s .eq()
method to select the element by its index. Here’s how you can modify your code:
مقالات ذات صلة
element you want, you can use jQuery’s .eq()
method to select the element by its index. Here’s how you can modify your code:javascript$('#accordion').append($('
').html(Agency));
if (Icon == 1) {
$('#accordion').find('h3').eq(-1).addClass('Icon');
}
AccordionChild = $('
');
AccordionChild.append("
").html(ToolsList);
$('#accordion').append(AccordionChild);
In this code, .find('h3')
is used to target all
elements within #accordion
, and .eq(-1)
is used to select the last
element added (the one you just appended) to apply the class Icon
. This should ensure that the class is only added to the specific
element you want.
element added (the one you just appended) to apply the class Icon
. This should ensure that the class is only added to the specific
element you want.
المزيد من المعلومات
من المهم أن تتأكد أن العنصر الذي تريد إضافة الكلاس إليه هو العنصر الصحيح. في الشيفرة التي قدمتها، الدالة addClass
تستهدف كل العناصر
في الصفحة، وليس العنصر الحالي الذي تم إنشاؤه. لحل هذه المشكلة، يمكنك استخدام طريقة أخرى لاستهداف العنصر الحالي.
بدلاً من استخدام $('h3').addClass('Icon');
يمكنك استخدام $('#accordion').children('h3:last-child').addClass('Icon');
لاستهداف آخر عنصر