2012-02-09 81 views
1

的我改變了我的鏈接網址以添加www.site.com/index.html?s=234 & DC = 65828添加字符串結束URL

我正在使用此代碼得到的是:網站.com/& dc = 65828

var target="&dc=65828"; 
$("a").attr({ 
href: "" + target 
}); 

有人可以告訴我我哪裏出錯了。

+0

當你調用這段代碼時'href'的值是多少?你能添加一個HTML例子嗎? – scottm 2012-02-09 16:03:20

+0

你想獲得每個變量的值嗎? – MG1 2012-02-09 16:03:40

回答

-2

試試這個:

var target="&dc=65828", 
    $link = $("a"); 

$link.attr('href', $link.attr('href') + target); 
+0

不,這將重置頁面上的所有鏈接以指向'&dc = 65828' – iblue 2012-02-09 16:06:06

+0

'$ link.attr('href')+ target'會正常工作。 – osahyoun 2012-02-09 16:08:50

3

我會做這樣的:

var target="&dc=65828"; 
$(function(){ 
    $('a').each(function(){ 
     $(this).attr('href', $(this).attr('href')+target); 
    }); 
}); 
+2

你不需要'.each'。當選擇器返回多個對象時,可以在'.attr'函數內引用'$(this)'。 – tkone 2012-02-09 16:06:21

+0

謝謝你的幫助。 – Blynn 2012-02-09 18:49:55

+0

@tkone:謝謝,我不知道;) – 2012-02-09 18:58:33

-1

有幾件事情。

第一:

href: ""+target

將設置你的鏈接只有:

&dc=65828

你需要這樣的:

$('a').attr('href', $(this).attr('href')+target);

但是,這是假設?s=234已經在鏈接的末尾。如果沒有,你也需要添加。

+0

你可以發佈一個jsFiddle來顯示這個工作嗎? – kapa 2012-02-10 11:13:12

-1

檢查了這一點,這是會給出確切的匹配結果

$('a').append(function(){ 
       $(this).attr('href', $(this).attr('href')+target); 
      }); 



    $('a').html(function(){ 
       $(this).attr('href', $(this).attr('href')+target); 
      }); 
3

這將是解決這個優雅的方式:

var target="&dc=65828"; 
$('a').attr('href', function(i, currentAttribute){ 
    return currentAttribute + target; 
}); 

傳遞作爲第二個參數的功能在其第二個參數(我將其命名爲currentAttribute以獲得更好的可讀性)中接收當前的href屬性。無論你從這個函數返回什麼,都將被設置爲新的href屬性。

此方法適用於多個鏈接,並且不使用不必要的.each()

1

你們不相信錯誤檢查?

$('a').attr('href', function(i, currentAttribute){ 
    // don't clutter up the global namespace 
    var target="dc=65828"; 
    // if it's already there, don't double-do it 
    if (currentAttribute.indexOf(target) >= 0){ 
     return currentAttribute; 
    } 
    // if we've got a query string already 
    if (currentAttribute.indexOf('?') >= 0){ 
     return currentAttribute + '&' + target; 
    } 
    // if we've not got a query string yet 
    return currentAttribute + '?' + target; 
}); 
+0

好吧,當有人刮掉問題代碼片段時,他們會很感激我想。 ;-) – madphp 2013-06-21 18:28:08