2010-10-30 42 views
1

我有在aspx頁面像一個錨鏈接:jQuery的href定位值

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

我需要使用jquery.How做這個訪問「myTag」的價值?

+0

你的價值的意思jQuery代碼?該ID? href?相關文字? – 2010-10-30 14:49:17

+0

對不起,我的問題實際上並不清楚。我只想要最後一部分的href,我的意思是「myTag」的值只有在這種情況下是'asp'。 – ANP 2010-10-30 14:56:55

回答

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/

+0

確實很棒。非常感謝。 – ANP 2010-10-31 05:59:09

+0

但有一件事情假設'myTag = asp net',那麼它給出結果'asp + net'。出現一個+符號,有沒有辦法讓輸出只能是'asp net'? – ANP 2010-10-31 06:04:33

+0

@ANP - 好的,只需在最後加上'.replace('+','')'即可。 – user113716 2010-10-31 12:52:48

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

http://jsfiddle.net/max6s/

+0

比接受的答案好得多。 – jcollum 2012-11-29 21:14:53

2

要獲得鏈接的href:

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

進去的HTML:

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

#Anchor是CSS格式的選擇,這意味着, 「選擇ID爲'Anchor'的元素。」

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> 

這裏是這個函數的用法:

警報(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> 

用法:

警報($ getAnchorValue( 'myTag',$( '#錨')ATTR(「HREF 「)));

編輯:我已經editted我的答案,並還增加了獲取查詢參數

+0

不錯,但它不是jQuery – 2010-10-30 15:33:00

+0

jQuery不是要求。要求是獲得標籤的價值。 – 2010-10-30 15:34:03

+1

「我需要使用jquery訪問」myTag「值。怎麼做? - 這是必需的。 – Marwelln 2010-10-30 21:12:36