Как изменить цвет динамически создаваемого элемента? - PullRequest
0 голосов
/ 19 апреля 2019

У меня есть этот динамически созданный класс, в котором есть 3 кнопки сбоку.

 for classroom in classrooms
   if classroom.author.id == user.id
      tr#bothcells
        td#classroomcell= classroom.classroomname
        td#buttonscell
           button.renameclassroom(data-toggle="tooltip", data-placement="top" ,title="Rename this classroom" type='button' style='font-size:15px', onclick='renameclassroom($(this))' value=classroom.id)
              i.fas.fa-pencil-alt
           button.showstudents(data-toggle="tooltip", data-placement="top" ,title="Show all students belonging to this classroom" style='font-size:15px' type='button',  onclick='get($(this))', value=classroom.id )
              i.fas.fa-user-graduate
           a.deleteclassroom(data-toggle="tooltip", data-placement="top" ,title="Delete this classroom" style='font-size:15px',href="/classroom/delete/" + classroom._id)
              i.fas.fa-times

.. и этот jQuery AJAX для получения имени учащихся, принадлежащих к этому классу.

function get(a){
  var classroomvalue = a.val();
  $.ajax({
    type: 'GET',
    url: 'http://localhost:8080/classroom/' + classroomvalue,
  })

  .done(function(data) {
    console.log('Get response:', JSON.stringify(data,  "", 2));
    $("#getResponse").html($(data).find('#students').html());
  })
  .fail(function(jqXHR, textStatus, err) {
    console.log('Ajax error response:', textStatus);
  });
};

Где я борюсь и какой у меня вопрос?Мне нужно изменить цвет значка кнопки при нажатии, так как классная комната и кнопки создаются динамически, я знаю, что не могу использовать Id, кроме значения.Мне действительно трудно найти решение, и я ничего не смог придумать.

ОБНОВЛЕНО HTML ОБРАЗОВАН enter image description here

1 Ответ

0 голосов
/ 19 апреля 2019

Прежде всего, иметь несколько элементов, имеющих один и тот же идентификатор, неверно, поскольку атрибут id предназначен для уникальной идентификации элемента. Кроме того, в этом случае вы можете избежать неприятностей с помощью следующего кода. Однако лучше использовать классы.

Код:

function get (a) {
  var classroomvalue = a.val();

  $.ajax({
    type: 'GET',
    url: 'http://localhost:8080/classroom/' + classroomvalue,
  })
  .done(function (data) {
    console.log('Get response:', JSON.stringify(data, "", 2));
    $("#getResponse").html($(data).find('#students').html());

    /* Reset the colour of all buttons' icons. */
    a.closest("tbody").find("tr button > i").css("color", "");

    /* Make the current button's icon's colour red. */
    a.children("i").css("color", "red");
  });
};
...