2013-07-26 31 views
2

我有一個jQuery函數來更改網頁上的href。如何讓這個腳本只在#container div內運行?使jQuery函數只能在特定的div ID或類中運行

$('a[href*="example.com"]').each(function(){ 
var index = this.href.indexOf(".com/"); 
this.href = this.href.slice(0, index+5) 
}) 

我試過這個,

$('#container').$('a[href*="example.com"]').each(function(){ 
var index = this.href.indexOf(".com/"); 
this.href = this.href.slice(0, index+5) 
}) 

,但它不工作。上面的代碼有什麼問題?

+0

您只能使用一個$(..)。一旦你有一個jQuery對象,你繼續鏈式語句:$('#container')。someFunction()。someOtherFunction()... – frenchie

+0

在它之前,我已經嘗試了每條語句的$()。像這樣$('#container')。('a [href * =「example.com」]'),但是它一樣,不起作用。 –

+0

@frenchie是否可以使用**('#container','a [href * ='example.com')**? –

回答

1

使用.find()

$('#container').find('a[href*="example.com"]').each(function(){ 
    var index = this.href.indexOf(".com/"); 
    this.href = this.href.slice(0, index+5) 
}) 

或者使用descendant selector

$('#container a[href*="example.com"]').each(function(){ 
    var index = this.href.indexOf(".com/"); 
    this.href = this.href.slice(0, index+5) 
}) 

您也可以嘗試每個語句稍有不同的版本

$('#container').find('a[href*="example.com"]').attr('href', function(idx, href){ 
    var index = href.indexOf(".com/"); 
    return href.slice(0, index + 5) 
}) 
+0

你不需要使用find,你可以將選擇器與一個空格合併。 – John

+0

哦,我的天哪,我忘了「找」部分..謝謝。我知道這個問題很容易,我會更多地瞭解jquery。謝謝.. –

+0

@John你認爲將選擇器與空間合併是什麼意思?如何 –

相關問題