2011-01-31 70 views
1

我有一些HTML這樣的:從JQuery中的錨標籤獲取值/相對url?

<span class="fetchSeries"><a href="sma10">10</a></span> 

我想要得到的值「sma10,」但是當我嘗試引用它的href屬性變成一個絕對路徑。有沒有辦法獲得錨標籤的相對路徑?

這裏就是我試圖完成:

  1. 綁定的自定義功能,點擊()針對跨距類=「fetchSeries」標籤中的任何鏈接。
  2. 提取該鏈接唯一的值(例如sma10)。

回答

3

如果唯一值是不是一個真正的HREF,您可以使用數據屬性:

HTML

<span class="fetchSeries"><a href="#" data-myvalue="sma10">10</a></span> 

的JavaScript

$('.fetchSeries a').click(function() { 
    var myval = $(this).data('myvalue'); 
}); 

文檔:http://api.jquery.com/data

2

使用THIC code

$(function(){ 
    var v = $('.fetchSeries a').attr('href'); 
    alert(v); 
}); 
+0

我會嘗試。問題是,當我在螢火蟲中查看「href」時,它顯示絕對網址,這不是我想要的。 – 2011-01-31 16:02:51

1

請參閱我的回答這個計算器帖子: Jquery how to trigger click event on href element

或者用純JavaScript

var parser = document.createElement('a'); 
parser.href = "http://example.com:3000/pathname/?search=test#hash"; 

parser.protocol; // => "http:" 
parser.hostname; // => "example.com" 
parser.port;  // => "3000" 
parser.pathname; // => "/pathname/" 
parser.search; // => "?search=test" 
parser.hash;  // => "#hash" 
parser.host;  // => "example.com:3000" 

https://gist.github.com/ldong/9735bcd2d3eca8c1038b

0

你可以使用的getAttribute來獲得相對性只要href的值與示例中的值相關即可。

document.getElementByID("theLink").getAttribute("href");