jQuery从已知的动态类名中获取元素ID名称

时间:2012-09-12 08:49:44

标签: jquery

我有一个值通过URL中的#传递这是一个复选框的类名,我想要做的是使用jQuery获取该复选框ID的值

// get hashtag value
if(self.document.location.hash){
var urlhash = self.document.location.hash;
var hashtagval = self.document.location.hash.replace("#","");

// get id of element from hashtagval (class name)
var counter = $('.'+hashtagval).attr('id');
}

1 个答案:

答案 0 :(得分:0)

好的,我测试了它,并且在散列中添加#a和#b可以正常工作。

除了你滥用哈希属性。 hash属性用于定义页面的视图状态(例如,屏幕应移至此段落),而不是存储一些本地变量,然后将其用于应用程序逻辑!

<!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Demo</title>
            <script src="jquery.js"></script>
            <script>
                $(document).ready(function() {
                    var change = true;
                    $('#ba').click(function() {
                        // get hashtag value
                        if(self.document.location.hash) {
                            var urlhash = self.document.location.hash;
                            var hashtagval = self.document.location.hash.replace("#", "");

                            // get id of element from hashtagval (class name)
                            var id = $('.' + hashtagval).attr('id');
                            $('body').append('<h1>id=' + id);
                        }
                    });
                });
            </script>
        </head>
        <body>

            <button type="button" id="ba" >
                Click Me!
            </button>

            <div>
                <p id="foundthisthing" class="a">
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </p>
                <p id="thisworkstoo"class="b">
                    eafdsaf dsa dgsf dgadg dfg dagfadgLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </p>
            </div>
        </body>
    </html>