window.location在以编程方式触发jQuery单击时出现故障

时间:2012-09-11 11:37:09

标签: jquery events redirect triggers window.location

考虑这个HTML

<table id="search_results">
    <tr><td><a href="reports.php" style="display:none">_</a>Report 1</td></tr>
</table>

我编写了一些代码,当鼠标点击TD的父级(TR)包含带有href属性的A标签时,窗口会被重定向到该页面:

//Set row clicking
$('table#search_results td').click(function () {
    var href = $(this).parent().find('a').attr("href");
    if (href) { window.location = href; }
});

当用户点击TD时,此代码可以正常运行。但是,我编写的代码在按下返回按钮时触发click事件。

$(document).keypress(function(e) {
    if(e.which == 13) {
        $('table#search_results tr:not([class=vanish]) td:first').click();
    }
});

我调试了代码。当按下返回按钮时,实际触发了click事件,并且正确填充了href变量,但页面只是刷新了?在URL的末尾,而不是被重定向到set href ...(例如,如果我在“index.php”并打算转到“reports.php”,而不是去那里,页面将使用url刷新“的index.php?”

为什么会这样?

2 个答案:

答案 0 :(得分:0)

我认为你打算做的是:

$(selector).trigger("click");

也:

window.location是一个对象。您可能想要设置的是window.location.href

http://davidwalsh.name/javascript-window-location

答案 1 :(得分:0)

修正了......我的错误......

本机表单提交正在接管jquery代码,即使表单没有操作且任何地方都没有提交按钮。我所要做的就是添加onsubmit =“return false;”在表格中。