获取 HTML data-*属性的值( 文章列表页面,存储文章id 为读取详细页面
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>把文章列表中文章id存储到data-*,并取出</title> <link rel="stylesheet" href="bootstrap-4.6.0-dist/css/bootstrap.min.css"> </head> <body> <p>If you click on me, I will disappear.</p> <div class="article2" data-article-id = "200">点击我取文章 id</div> <div class="article2" data-article-id = "300">点击我取文章2 id</div> <script src="bootstrap-4.6.0-dist/js/jquery-3.5.1.js"></script> <!-- <script src="bootstrap-4.6.0-dist/js/bootstrap.bundle.js"></script> --> </body> </html> <script type="text/javascript"> // $("p").hide(); $(document).ready( //onclick为指定元素添加点击事件 $(".article2").click(function(){ this.style.color="red" // alert(this.dataset.articleId) console.log($(".article2")); //文章篇数 let articles=$(".article2") for (var i = 0; i < articles.length; i++) { console.log(i); //打印文章的id到控制台 console.log(articles[i].dataset.articleId); } }) ); </script>
需求
网页无序列表,列出多篇文章,点击查看详细文章,要传递文章id,可以考虑存储在html语言标签的 data-* 属性上
1:原生js实现
<!DOCTYPE html>
<html>
<head>
<script>
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
alert(animal.innerHTML + "是一种" + animalType + "。");
}
</script>
</head>
<body>
<h1>物种</h1>
<p>点击某个物种来查看其类别:</p>
<ul>
<li onclick="showDetails(this)" id="owl" data-animal-type="鸟类">喜鹊</li>
<li onclick="showDetails(this)" id="salmon" data-animal-type="鱼类">金枪鱼</li>
<li onclick="showDetails(this)" id="tarantula" data-animal-type="蜘蛛">蝇虎</li>
</ul>
</body>
</html>
2: jquery实现
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>bootStrap4习</title>
<link rel="stylesheet" href="bootstrap-4.6.0-dist/css/bootstrap.min.css">
</head>
<body>
<p>If you click on me, I will disappear.</p>
<div class="article2" data-article-id = "200">点击我取文章 id</div>
<div class="article2" data-article-id = "300">点击我取文章2 id</div>
<!--<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" ></script>-->
<script src="bootstrap-4.6.0-dist/js/jquery-3.5.1.js"></script>
<!-- <script src="bootstrap-4.6.0-dist/js/bootstrap.bundle.js"></script> -->
</body>
</html>
<script type="text/javascript">
// $("p").hide();
$(document).ready(
//onclick为指定元素添加点击事件
$(".article2").click(function(){
this.style.color="red"
alert(this.dataset.articleId)
})
);
</script>
3: 在ui li列表中,能过html 的data-I属性,放在类上并取了打印到控制台
做产品的程序,才是好的程序员!