2011-02-09 97 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'); 
});