猿问

document.getElementById().value 不起作用

我一直在做一个关于员工的项目所以mysql数据库中有一些数据。为了得到它并将其放入 html 表中,我使用了 php.ini。


$sql = "SELECT * FROM Stock_Management.`staff_details`";

$result = mysqli_query($conn, $sql);


if(mysqli_num_rows($result)){

    while($row = mysqli_fetch_assoc($result)){

        echo "<tr>

                <td scope='row'>".$row['id']."</td>

                <td>".$row['fname']."</td>

                <td>".$row['lname']."</td>

                <td>".$row['phno']."</td>

                <td>".$row['employee_address']."</td>

                <td>".$row['join_date']."</td>

                <td><i class='far fa-edit btnedit' value=".$row['id']." name='btn-edit' id='btn-edit' onclick='edit()' style='color: green; cursor: pointer'></i></td>

                <td><i class='far fa-trash-alt btndelete' value='".$row['id']."' name='btn-delete' id='btn-delete' onclick='delete()' style='color: tomato; cursor: pointer'></i></td>

            </tr>";

    }

}

因此,如果您看到最后两个td标签,您可以看到我使用了 font Awesome 并values分别为它们提供了name和id属性。还有onclick带有函数的事件。


echo "<script>

    function edit(){

        let data_id = document.getElementById('btn-edit');

        console.log(data_id.value);

    }

</script>";

但每次我进入undefined控制台时。那么我的代码有什么问题。请帮我!!请。


汪汪一只猫
浏览 244回答 3
3回答

慕虎7371278

将元素中的“值”更改为data-value更改 javascript 行 'console.log(data_id.value);' 到console.log(data_id.dataset.value);此外,该<i>元素不包含该value属性。

慕慕森

为了获取该值,您可以将js代码更改为:function&nbsp;edit(){ &nbsp;&nbsp;&nbsp;&nbsp;console.log(event.target.value) }通过单击它,浏览器会创建事件,您可以将其作为目标来获取单击值。另外,您在值 value=".$row['id']." 周围缺少“'”。请记住,您不应在页面上多次出现相同的 id,因此如果您有多个具有此 id 的元素,则定位 btn-edit 永远不会起作用。您不应该对按钮使用“”标签

撒科打诨

.你不能向标签添加值和名称<i>,你应该使用输入标签,2.如果你使用这个,我希望你不会有任何问题;<label class='far fa-edit btnedit' onclick='edit()' style='color: green; cursor: pointer;font-size: 25px;'>&nbsp; &nbsp; <input type='hidden' id='btn-edit' name='btn_edit' value='".$row['id']."'/></label><script>&nbsp; &nbsp; function edit(){&nbsp; &nbsp; &nbsp; &nbsp; let data_id = document.getElementById('btn-edit');&nbsp; &nbsp; &nbsp; &nbsp; console.log(data_id.value);&nbsp; &nbsp; }</script>
随时随地看视频慕课网APP
我要回答