我有一个脚本如下
$('.button1').click(function() {
document.location.href=$(this).attr('id');
});
button1 具有可变的唯一 ID。单击时,页面必须重定向到网址“www.example.com/index.php?id=buttonid
”,但现在页面仅重定向到“button id
” .
我想在当前网址之前添加字符串“www.example.com/index.php?id=
”。我怎样才能做到这一点?
最佳答案
$('.button1').click(function() {
window.location = "www.example.com/index.php?id=" + this.id;
});
首先,使用 window.location
更好,因为根据规范 document.location
值是只读的,可能会导致您在旧版/不同浏览器中感到头痛。查看笔记@MDC DOM document.location page
对于第二个 - 使用 attr
jQuery 方法来获取 id 是一个不好的做法 - 你应该使用直接的原生 DOM 访问器 this.id
作为分配给 this
是普通的 DOM 元素。
关于jquery - 单击按钮转到链接 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4944387/