简体   繁体   English

无法从 HTML 数据集中访问值

[英]Cant access value from the HTML dataset

I am using Dataset to get some different values when doing drag and drop from one div to another.在从一个 div 拖放到另一个 div 时,我使用 Dataset 来获取一些不同的值。 but I am not able to access the additional attributes such as data-customerId when I call the Javascript function.但是当我调用 Javascript function 时,我无法访问其他属性,例如data-customerId

HTML with PHP dynamic data: HTML 与 PHP 动态数据:

<fieldset id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
    <legend style="color:cadetblue; border:white; width:auto; font:bold">Vacant parking spots</legend>
    <?php $counter = 0; foreach ($sql_get_vacant_spots_results_ as $row) { ?>
        <div id="<?php echo $counter; ?>" data-customerid="<?php echo $arr_users[0]['customer_id']; ?>" data-y="<?php echo $row['spot_no'] ?>" data-z="<?php echo $row['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" ondragstart="drag(event)" width="88" height="31">
            <labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $row['spot_no'] . ' Gate: ' . $row['parking_gate_id'] ?></label>
        </div>
    <?php $counter++; } ?>
</fieldset>

<fieldset id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
    <legend style="color:cadetblue; border:white; width:auto; font:bold">Current parking spots of the customer</legend>
    <?php $count = 0; foreach ($arr_users as $user) { ?>
        <div id="<?php echo $count ?>" data-customerid="<?php echo $user['customer_id'] ?>" data-y="<?php echo $user['spot_id'] ?>" data-z="<?php echo $user['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" width="88" height="31">
            <labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $user['spot_id'] . ' Gate: ' .  $user['gate_id'] ?></label>
        </div>
    <?php $count++; } ?>
</fieldset>

And here is the Javascript:这是 Javascript:

   function drop(ev) {
        const el = document.querySelector('#' +ev.dataTransfer.getData("text")); //prints: Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#33' is not a valid selector.
        console.log('drop', el.dataset.customerid);
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }

Fixed by accessing the id like this:通过像这样访问 id 来修复:

const el = document.querySelector("[id=" + "\'" + ev.dataTransfer.getData("text") + "\'" + "]");

EDIT:编辑:

Html element id: Html 元件编号:

id="count_id<?php echo $counter; ?>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM