我的代码有问题,因为我通常使用(例如按钮)ID 来引用元素,例如:
$(document).ready(function () {
$('.delete_imgs').click(function () {
id = $(this).attr('id');
$('.confirm_delete').css({
visibility: "visible"
});
});
});
因此,如果单击任何 .delete_imgs
按钮,则执行该功能。并且还使用 this
函数来引用在 HTML 文档中被点击的元素。
上面的 id
来自这里的一个 php 函数:
while($stmt -> fetch()){
echo "<tr><td>
<img class='delete_imgs' id='$matchid' src='Images/delete_icon.png'>
<img class='edit_imgs' id='$matchid'src='Images/edit_icon.png'></td>
<td>$hero</td>
<td>$result</td>
<td>$gamemode</td>
<td>$mmr</td>
</tr>";
}
在添加 edit_imgs
图像之前这很好,因为所有 delete_imgs
都会有不同的 ID(匹配 ID 是唯一的)。但是现在,我不应该使用相同的 ID 编辑和删除图像,所以我不确定如何为 javascript/jQuery 函数引用它们。
如果这是一个相当宽泛的问题,我深表歉意,如有必要,我可以添加更多信息:
问题的简短版本:如何在不使用 ID 或类的情况下引用多个 HTML 元素?
编辑:这是我最终将使用 ID 的目的:
function deletematch(){
$.ajax({
type:"POST",
url:"php/RemoveMatch.php", //This code sends the variable with the match
data: "match_id=" + id, //id in it to the php file and executes the deletion.
success: function(){
alert("The match has been deleted");
$('.confirm_delete').css({visibility:"hidden"});
}
});
}
编辑匹配尚未编码。
最佳答案
尝试使用数据属性而不是“id”。这样他们就可以共享相同的 ID 而不必违反标准。请注意,我假设“delete_imgs”和“edit_imgs”有自己的风格,所以我避免改变它们。
while($stmt -> fetch()){
echo "<tr><td>
<img class='delete_imgs' data-id='$matchid' src='Images/delete_icon.png'>
<img class='edit_imgs' data-id='$matchid'src='Images/edit_icon.png'></td>
<td>$hero</td>
<td>$result</td>
<td>$gamemode</td>
<td>$mmr</td>
</tr>";
}
然后您可以像这样在您的 JS 中获取 ID:
$('.delete_imgs').click(function () {
id = $(this).data('id');
});
您也可以同时选择它们:
$('[data-id="id-goes-here"]').click(function() {
// do something
});
但是,如果您想要一种简单的方法在不知道 ID 的情况下引用它们,我会添加另一个数据属性或类。例如
// You can use the selector above: $('[data-type="action"]')
<img class='delete_imgs' data-type="action" data-id='$matchid' src='Images/delete_icon.png'>
<img class='edit_imgs' data-type="action" data-id='$matchid'src='Images/edit_icon.png'>
或者
// Select with: $('.action')
<img class='delete_imgs action' data-id='$matchid' src='Images/delete_icon.png'>
<img class='edit_imgs action' data-id='$matchid'src='Images/edit_icon.png'>
关于javascript - 如何引用多个 HTML 元素以用于 javascript/jQuery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21598073/