【问题标题】:How to access element through variable ID in JqueryjQuery中如何通过变量ID访问元素
【发布时间】:2022-01-23 22:45:26
【问题描述】:

我正在编写一个代码,我想通过 Jquery 检查单选按钮,有一些链接,当我单击特定链接时,它会检查单选按钮,单选按钮的 Id 被传递给 jquery click 函数,我得到该 id 并将其存储在变量中,如何通过 var id 访问该单选按钮元素!!!!

//Html
<ul class="footer-links">
  <li>Services</li>
  <li><a href="#scrollup-content" data-id="tab-1">Brand Management</a></li>
  <li><a href="#scrollup-content" data-id="tab-2">In & Outdoor Signage</a></label></li>
</ul>

//jquery
$(".footer-links li a").on("click",function(){
        var id = $(this).data();
        console.log(id)
        $('#tab-2').attr('checked', true); // this is working properly
        $('#id').attr('checked', true);// how to do? I want this to work
    })

【问题讨论】:

    标签: html jquery radio-button element var


    【解决方案1】:

    我认为 HTML 部分中的元素存在问题:我看不到您在文件中添加了单选按钮。查看下面的示例代码:

    $('#radioButtonForm input').on('change', function() {
       alert($('input[name=radioName]:checked', '#radioButtonForm').val()); 
    });
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <title>Test Project</title>
    </head>
    
    <body>
        <form id="radioButtonForm">
            <ul>
                <li>Services</li>
    
                <li>
                    <input type="radio" name="radioName" value="1" />Brand Management<br />
                </li>
    
                <li>
                    <input type="radio" name="radioName" value="2" />In&Outdoor Signage<br />
                </li>
            </ul>
        </form>
    </body>
    
    </html>

    【讨论】:

    • 单选按钮在#scrollup 部分,问题不在于html,当我尝试访问它时 $("#tab-2) 它工作正常,但我想通过变量 id 使复选框工作,
    • var id = $(this).data("id");
    • 我没有看到id"id" 的元素:$('#id').attr('checked', true);
    猜你喜欢
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多