2011-02-09 112 views
25

我有一個腳本如下去按鈕點擊鏈接 - jQuery的

$('.button1').click(function() { 
    document.location.href=$(this).attr('id'); 
}); 

Button1的具有可變的唯一的ID。點擊後,頁面必須重定向到url「www.example.com/index.php?id=buttonid」,但現在該頁面僅重定向到「button id」。

我想在當前url之前添加字符串「www.example.com/index.php?id=」。我怎樣才能使這成爲可能?

回答

55
$('.button1').click(function() { 
    window.location = "www.example.com/index.php?id=" + this.id; 
}); 

首先使用window.location更好,因爲根據規格document.location值是隻讀的,可能會導致您在較舊/不同瀏覽器中頭痛。檢查筆記@MDC DOM document.location page

而對於第二個 - 使用jQuery的attr方法獲取ID是一種不好的做法 - 你應該使用本機直接訪問DOM作爲this.id分配給this值是正常的DOM元素。

2

爲什麼不只是改變第二行

document.location.href="www.example.com/index.php?id=" + $(this).attr('id'); 
+0

謝謝...這個作品.. :) – 2011-02-09 11:48:39

+0

@blasteralfred檢查我的回答對一些更多的技巧和良好做法 – 2011-02-09 11:51:08

4

您需要指定域:

$('.button1').click(function() { 
    window.location = 'www.example.com/index.php?id=' + this.id; 
}); 
+0

謝謝...這個作品.. :) – 2011-02-09 11:48:08

5
$('.button1').click(function() { 
    document.location.href='/index.php?id=' + $(this).attr('id'); 
});