如何在 jQuery 中获取并使用它来获取 data 属性的值?

jqueryweb developmentfront end technology

要获取 data 属性的值,请使用 −

$(“yourSelector”).data()

以下是带有 data 属性的输入框示例 −

<input type="text" id="txtValue" src="" data-value="90">

示例

以下是代码 −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <input type="text" id="txtValue" src="" data-value="90">
</body>
<script>
   var value = $('#txtValue').data('value');
   console.log("The value is=" + value);
</script>
</html>

输出

输出如下 −


相关文章