0

我有一个通过 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');
}
4

1 回答 1

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>
于 2012-09-12T08:59:23.677 回答