如何从click事件处理程序中获取ID?

时间:2018-05-06 15:20:56

标签: javascript jquery

我正在尝试创建一个ID作为模式的选择器,然后我将能够访问显示属性。

   $.ajax({
      url: 'https://randomuser.me/api/?results=12',
      dataType: 'json',
      success: function(data) {
        console.log(data);
        employees = data.results;
        $.each(employees, function (i, employee) { 

    newHTML += '<div id="' + i + '" class="container">';
    newHTML += '<div class="employee-img-container">';
    newHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
    newHTML += '</div>';
    newHTML += '<div class="employee-info-container">';
    newHTML += '<h3 class="employee-name">' + employee.name.first + ' ' + employee.name.last + '</h3>';
    newHTML += '<p class="employee-email">' + employee.email + '</p>';
    newHTML += '<p class="employee-location">' + employee.location.city + ', ' + employee.location.state + '</p>';
    newHTML += '</div></div></div></div>';

    employeeArr.push(employee);

    modalHTML += '<div id="modal' + i + '" class="modal">';
    modalHTML += '<div class="modal-content">';
    modalHTML += '<div class="modal-header">';
    modalHTML += '<span class="close">&times;</span>';
    modalHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
    modalHTML += '<h2 class= emp-modal-name>' + employee.name.first + ' ' + employee.name.last + '</h2>';
    modalHTML += '</div';
    modalHTML += '<div class="modal-body">';
    modalHTML += '<p>Employee Info</p>';
    modalHTML += '</div></div></div>';

    modalArr.push(employee);

    });
    $('.grid-container').html(newHTML);
    $('.modal-container').html(modalHTML);
        $('.container').on('click', function (event) {
            console.log(event.currentTarget.id);
            let newId = '#modal' + event.currentTarget.id;
            let displayModal = $(newId)
            let display = document.querySelector(newId);
            //displayModal.style.display = 'block';
            console.log(displayModal);
            console.log(display);
            console.log(newId);

});
}
});

当我记录event.currentTarget.id时,我得到一个数字,我也可以创建一个我想用作选择器的字符串。我无法弄清楚如何将它用作实际部门。不确定我是否需要使用if语句将其与我想要显示的模态类的id进行比较。谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

$(document).ready(function() {
    $("a").click(function(event) {
        alert(event.target.id);
    });
});