我正在尝试编写一个脚本,该脚本将在单击时从数据库返回一个唯一 ID。我尝试阅读不同的论坛以找到解决方案,但不幸的是,我还没有找到任何有用的东西。
<?php
$table = mysqli_query($conn ,'SELECT * FROM content');
while($row = mysqli_fetch_array($table)){ ?>
<tr id="<?php echo $row['uidContent']; ?>">
<td width="200" data-target="themeContent"><?php echo $row['themeContent']; ?></td>
<td width="300" data-target="visualIdeaContent"><?php echo $row['visualIdeaContent']; ?></td>
<td width="600" data-target="captionContent"><?php echo $row['captionContent']; ?></td>
<td width="100" data-target="dateContent"><?php echo $row['dateContent']; ?></td>
<td width="200" data-target="visualContent"><img src="<?php echo $row['visualContent']; ?>"width="200"/></td>
<td width="170">
<a class="badge badge-primary p-2" role="button" data-target="linkContent" href="<?php echo $row['linkContent']; ?>" target="_blank">Link</a>
<a class="badge badge-success p-2" href="#" data-role="update" data-id="<?php echo $row['uidContent'] ;?>">Edit</a>
<a class="badge badge-danger p-2" role="button" href="action.inc.php?delete=<?php echo $row['uidContent'] ;?>" >Delete</a>
</td>
</tr>
<?php }
?>
唯一ID通过“data-id”存储在这行代码中
<a class="badge badge-success p-2" href="#" data-role="update" data-id="<?php echo $row['uidContent'] ;?>">Edit</a>
JavaScript
<script>
$(document).ready(function(){
$(document).on('click','a[data-role=update]',function(){
alert($(this).data('uidContent'));
});
});
</script>
我希望 localhost 返回唯一 ID (例如,“localhost: 2066”),但它返回的结果是 “localhost: undefined”... 起初,我认为这是我的数据库的问题,但现在我了解到情况并非如此,因为当我检查有问题的按钮时会显示独特的想法。 Screenshot of the IDs
最佳答案
数据参数应该是data('id')
。使用 $(this).data('id')
而不是 $(this).data('uidContent')
。
jQuery .data() takes the argument after the - separator. For example: if an HTML attributes is
data-id="localhost: 2066"
then to get this attribute value we have to call like$(selector).data('id')
.
示例代码:
$(document).ready(function(){
$(document).on('click','a[data-role=update]', function() {
alert($(this).data('id'));
// ^^^^^^
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="badge badge-success p-2" href="#" data-role="update" data-id="localhost: 2066">Edit</a>
关于javascript - Localhost 返回 "Undefined"而不是唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57104697/