简体   繁体   English

单击按钮显示属性

[英]Show attribute on button click

Hi I am starting with JQuery, sorry for the simple question, I just can´t seem to find an answer. 嗨,我从JQuery开始,很抱歉这个简单的问题,我似乎找不到答案。 There are two HTML links with class "button" and different IDs. 有两个HTML链接,它们具有“按钮”类和不同的ID。 When you click on a link, I need it to alert the appropriate ID. 当您单击链接时,我需要它来提醒相应的ID。 However they both alert ID from the first link. 但是,它们都从第一个链接发出警报ID。 How to modify the code so that both links alert their ID? 如何修改代码,以便两个链接都提示其ID?

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>
<a href="#" class="button" id = "1"> test1 </a> <br><br>
<a href="#" class="button" id = "2"> test2 </a>
</body>

<script>
$(".button").click(function(){
    alert($(".button").attr("id"));
});
</script>

</html>

you need to targeted the clicked button using this keyword alert($(this).attr("id")); 您需要使用this关键字alert($(this).attr("id"));来定位单击按钮的目标alert($(this).attr("id"));

 <!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>
<a href="#" class="button" id = "1"> test1 </a> <br><br>
<a href="#" class="button" id = "2"> test2 </a>
</body>

<script>
$(".button").click(function(){
    alert($(this).attr("id"));
});
</script>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM