2012-01-09 68 views
0

林試圖從例如URL最後一個字符串...獲得來自URL最後一個字符串使用jQuery

http://www.mywebsite/blog/this-post 

我想使用jQuery獲得「這個-後」 伊夫以下.. 。

$('img.gigthumb').each(function(){ 
    var foo = $(this).parent().attr('href').split('/'); 
    $(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[1]+'.jpg'); 
}) 

只有它不起作用,我認爲這是因爲我在URL中有多個'/',任何想法如何只針對最後?

希望這是有道理的!

+0

[jQuery解析我們的URL路徑的一部分]的可能重複(http://stackoverflow.com/questions/6894093/jquery-to-parse-our-a-part-of-a-url-路徑) – 2012-01-09 20:31:32

+0

你好,我只是認爲這是撥款讓你知道回放'.pop()'和'arr [arr.length-1]的性能。「http://jsperf.com/pop-vs-arr-length-1 – ajax333221 2012-01-10 01:39:59

回答

5

這正是.pop()由爲:

$('img.gigthumb').each(function(){ 
    var foo = $(this).parent().attr('href').split('/').pop(); 
    $(this).attr('src','/lic/wp-content/uploads/2012/01/' + foo + '.jpg'); 
}); 
+0

+1在這種情況下從未想過流行。 – 2012-01-09 20:35:25

+0

哇,從未聽說過.pop之前,非常感謝! – Liam 2012-01-09 20:38:23

+1

我對我使用'.pop()'而不是'foo [foo.length-1]' – ajax333221 2012-01-09 21:20:28

1

不要用foo指數1使用的元素,但最後一個:

$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[foo.length-1]+'.jpg'); 
0

按照您的例子中,你所需要的分裂的最後部分:

$('img.gigthumb').each(function(){ 
    var foo = $(this).parent().attr('href').split('/'); 
    var last = foo.length - 1; 
    $(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[last]+'.jpg'); 
}) 
0
var foo = $(this).parent().attr('href').replace(/^.*\\/, ''); 
1

拆分以「/」會給你的數組:如果你想要得到的最後一個項目,無論數組的大小做

foo[0] = "http:" 
foo[1] = "" 
foo[2] = "www.mywebsite" 
foo[3] = "blog" 
foo[4] = "this-post" 

foo[foo.length - 1] 

或約瑟夫提到: foo.pop()

+1

+1'.pop()'由於它正在修改數組(通過刪除最後一項)而變慢。這裏是證明http://jsperf.com/pop-vs-arr-length-1 – ajax333221 2012-01-10 01:35:21

相關問題