首页 > 解决方案 > 如何使用 jquery 从超链接 onclick 中获取 id?

问题描述

我有包含 `class="candidate_type" 的超链接。我想单击一个按钮并显示带有候选类型 ID 的锚的 ID。

<script>
    $(document).ready(function(){
        $("#continue").click(function(){
            candidate_type = $(".candidate_type").attr('id');
            alert(candidate_type);
        });
    });
</script>

<a class="candidate_type" id="Employer">I`m Employer</a>
<a class="candidate_type" id="Consultant">I`m Consultant</a>

<a href="javascript:void(0)" id="continue" class="btn-new">Continue</a>

谢谢你

标签: javascriptjquery

解决方案


You have more than one candidate_type elements, to get id of all elements you can iterate over it using .each as shown below

    $(document).ready(function(){
        $("#continue").click(function(){
            $(".candidate_type").each(function(){
              var candidate_type = $(this).attr('id');
              alert(candidate_type);
            });
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="candidate_type" id="Employer">I`m Employer</a>
<a class="candidate_type" id="Consultant">I`m Consultant</a>

<a href="javascript:void(0)" id="continue" class="btn-new">Continue</a>


推荐阅读