Jquery href锚点值

时间:2010-10-30 14:48:03

标签: jquery anchor

我在aspx页面中有一个锚点链接,如:

<a id="Anchor"class="myAnchor" href="Myproject/Mypage.aspx?myTag=asp">Go</a>

我需要使用jquery来访问“myTag”值。如何做到这一点?

4 个答案:

答案 0 :(得分:11)

$(function(ready){
    alert($('#Anchor').attr('href')); // prints Myproject/Mypage.aspx?tag=asp
    alert($('#Anchor').text()); // prints Go
});

http://jsfiddle.net/max6s/

答案 1 :(得分:3)

你可以这样做:

var myTag = $('#Anchor')[0].search.split('=')[1];

示例: http://jsfiddle.net/B6GYB/

或者不使用jQuery:

var myTag = document.getElementById('Anchor').search.split('=')[1];

示例: http://jsfiddle.net/B6GYB/1/

答案 2 :(得分:2)

获取链接的href:

var href = $('#Anchor').attr('href');

要获取HTML内容:

var html = $('#Anchor').html();

#Anchor是CSS格式选择器,表示“选择ID为'Anchor'的元素。”

答案 3 :(得分:0)

您可以使用以下代码获取url的特定查询参数:

<强>的Javascript

<script type="text/javascript">
        function getAnchorValue(anchorId, key) {
            var href = document.getElementById(anchorId).getAttribute('href');
            var pageQuerySearch = new PageQuery(href.split('?')[1]);
            return unescape(unescape(pageQuerySearch.getValue(key)));
        }
        function PageQuery(query) {
            if (query.length > 1) {this.q = query; } else { this.q = null; } this.keyValuePairs = new Array();
            if (this.q) { for (var i = 0; i < this.q.split("&").length; i++) { this.keyValuePairs[i] = this.q.split("&")[i]; } };
            this.getValue = function (s) {
                for (var j = 0; j < this.keyValuePairs.length; j++) {
                    if (this.keyValuePairs[j].split("=")[0] == s) { return this.keyValuePairs[j].split("=")[1]; }
                } return false;
            };
        }
</script>

以下是此功能的用法:

  

alert(getAnchorValue('Anchor','myTag'));

<强> JQuery的

<script type="text/javascript">
    ; (function ($) {
        $.extend({
            getAnchorValue: function (name, url) {
                function getQueryStringParams() {
                    var parameters = {}, e, a = /\+/g, r = /([^&=]+)=?([^&]*)/g,
                        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                        q = url ? url.split('?')[1] : window.location.search.substring(1);
                    while (e = r.exec(q)) { parameters[d(e[1])] = d(e[2]) }; return parameters;
                }
                if (!this.params) this.params = getQueryStringParams();
                return this.params[name];
            }
        });
    })(jQuery);
</script>

用法:

  

alert($。getAnchorValue('myTag',$('#Anchor')。attr('href')));

编辑:我编写了我的答案并添加了用于获取查询字符串参数的jquery代码