php 如何访问js中的特定元素?

mw3dktmi  于 2023-05-16  发布在  PHP
关注(0)|答案(2)|浏览(68)

当我点击某个元素时,我想为被点击的元素显示菜单。

让它看起来像屏幕截图。在未来,通过点击“编辑”或“删除”跨度,它将编辑或删除用户所选字段的数据。

<?php
$checkProducts = mysqli_query($connect, "SELECT * FROM `products`");
while ($resCheckProduct = mysqli_fetch_assoc($checkProducts)) {
    $checkUnits = mysqli_query($connect, "SELECT * FROM `units` WHERE id_unit = {$resCheckProduct['unit']}");
    while ($resCheckUnits = mysqli_fetch_assoc($checkUnits)) {
?>

        <tr class="tr-content">
            <td><input type="checkbox" name="" id=""></td>
            <td><span class="icon-menu-span" data-id="<?= $resCheckProduct['id_product'] ?>"></span>
                <div class="table-div-menu-product" data-id="<?= $resCheckProduct['id_product'] ?>">
                    <span>edit</span>
                    <span>delete</span>
                </div>
            </td>
            <td><?= $resCheckProduct['name'] ?></td>
            <td><?= $resCheckProduct['description'] ?></td>
            <td><img class="tableProduct-img" src="<?= $resCheckProduct['image'] ?>" alt=""></td>
            <td><?= $resCheckProduct['available_balance'] ?></td>
            <td><?= $resCheckUnits['abbreviated'] ?></td>
            <td><?= $resCheckProduct['retail_price'] ?>₽</td>
            <td><?= $resCheckProduct['purchase_price'] ?>₽</td>
            <td><?= $resCheckProduct['date_of_creation'] ?></td>
            <td><?= $resCheckProduct['date_of_change'] ?></td>
        </tr>

<?php
    }
}
?>
var
    butOpenWindowMenu = document.getElementsByClassName('icon-menu-span')[butOpenWindowMenu.dataset.id],
    modalWindowMenu = document.getElementsByClassName('table-div-menu-product')[modalWindowMenu.dataset.id];

butOpenWindowMenu.addEventListener('click', function (e) {
    e.preventDefault();
    modalWindowMenu.style.display = 'block';
});

window.addEventListener('click', function (modal) {
    if (modal.target == modalWindowMenu) {
        modalWindowMenu.style.display = 'none';
    }
});
t40tm48m

t40tm48m1#

我想你应该这样做来打开它们:

var butOpenWindowMenus = document.querySelectorAll('.icon-menu-span');

for (var butOpenWindowMenu of butOpenWindowMenus) {
  butOpenWindowMenu.addEventListener('click', function() {
    document.querySelector('.table-div-menu-product[data-id="'+this.dataset.id+'"]).style.display = 'block';
  })
}
pokxtpni

pokxtpni2#

您可以使用querySelector并传递css选择器document.querySelector('icon-menu-span[data-id=*]')
你也可以从点击的目标中获取数据ID,并在CSS选择器中使用它来打开该元素,或者使用相对DOM导航来更新菜单项。
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

相关问题