我尝试从数据属性获取值并传递给Java脚本变量,但它给出了未定义的值
$(document).on("click","#edit_cust",function(){
var customer_id=$(this).data("id");
var customer_name=$(this).data("name");
var customer_phone=$(this).data("phone");
var customer_addr=$(this).data("mail");
var customer_mail=$(this).data("phone");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='btn-group' role='group' >
<a id="edit_cust" data-target="#edit" data-toggle="modal"><button
type='button' class='btn btn-primary btn-sm' data-id="<?php echo
$customer["cus_id"]; ?>" data-name="<?php echo $customer["cus_name"]; ?>"
data-phone="<?php echo $customer["cus_phone"]; ?>" data-addr="<?php echo
$customer["cus_address"]; ?>" data-mail="<?php echo $customer["cus_mail"]; ?
>"><span class="fas fa-user-edit edit_data" aria-hidden='true'></span>
</button></a>
</div>
最佳答案
内部button
都具有所有这些数据属性,因此请在单击的元素内获取button
。
$(document).on("click","#edit_cust",function(){
// cache buttton reference
var $btn = $('button', this);
// or $btn = $(this).find('button');
// get values from button
var customer_id = $(btn.data("id");
var customer_name = $btn.data("name");
var customer_phone = $btn.data("phone");
var customer_addr = $btn.data("mail");
var customer_mail = $btn.data("phone");
});