jQuery 获取data参数值
jQuery 获取data参数经常被使用到,单个的选择器如获取某个id的data参数或者多个的选择器获取被点击的data参数。
1、单个 - jQuery 获取选择器的data参数
比如HTML
<button type="button" onclick="getButData()" id="butVal" data-but-val = "单个data值">
JavaScript代码
function getButData(){ let but_val = $("#butVal").data("but-val"); alert('点击显示 '+ but_val); }
2、多个 - jQuery 获取点击的data
比如HTML
<ul> <li class="getDataValue" data-id = '1' data-title="PHP title值"> PHP </li> <li class="getDataValue" data-id = '2' data-title="HTML title值" > HTML </li> <li class="getDataValue" data-id = '3' data-title="JavaScript title值"> JavaScript </li> <li class="getDataValue" data-id = '4' data-title="jQuery title值"> jQuery </li> </ul>
JavaScript代码
$(".getDataValue").click(function () {//或者 $("ul li").click(function () { let id = $(this).data("id"); let title = $(this).data("title"); alert("你点击了 >> id:"+id+" - title:"+title); });
完整示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jq 获取data参数值</title> </head> <body> <button type="button" onclick="getButData()" id="butVal" data-but-val = "单个data值"> 点击显示 </button> <br /> <ul> <li class="getDataValue" data-id = '1' data-title="PHP title值"> PHP </li> <li class="getDataValue" data-id = '2' data-title="HTML title值" > HTML </li> <li class="getDataValue" data-id = '3' data-title="JavaScript title值"> JavaScript </li> <li class="getDataValue" data-id = '4' data-title="jQuery title值"> jQuery </li> </ul> <script src="https://xkbooks.com/unit/js/jquery-3.3.1.min.js"></script> <script> function getButData(){ let but_val = $("#butVal").data("but-val"); alert('点击显示 '+ but_val); } $(".getDataValue").click(function () {//或者 $("ul li").click(function () { let id = $(this).data("id"); let title = $(this).data("title"); alert("你点击了 >> id:"+id+" - title:"+title); }); </script> </body> </html>