当前位置: 首页 > 图文教程 > 网络编程 > Javascript > window.location.href出问题分析思路

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 window.location.href出问题分析思路


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 455 ::
收藏到网摘: n/a

今天在公司给别的同事改bug,其中一个是window.location.href  不起作用

alert(”ok”)
window.location.href = ‘/event/index.php?from_city=’ + site;

上面的alert(”ok”);是不跳转后用来调试的,页面反映为现实url的值,但不进行跳转,分析思路是window.location.href出问题,所以尝试了常用的调试方式,比如:

判断是否是在包含页里面:采用

window.parent.location.href=url; //这个完全否决,因为不是这种情况

采用 window.href location.href document.href均无效

于是跳出判断函数内部出错,分析页面出发该函数的事件,原来是这样的:

<a href=”javascript:void(0)” onclick=”changeSite(’200′)”>

发现问题:<a href=”javascript:void(0)” ,于是修改为:

<a href=”javascript:changeSite(’200′)”>

于是一切正常!

为什么会发生这个问题呢?我们来看看javascript:void(0) :

JavaScript中void是一个操作符,该操作符指定要计算一个表达式但是不返回值。

void 操作符用法格式如下:
1. javascript:void (expression)
2. javascript:void expression

expression 是一个要计算的 JavaScript 标准的表达式。表达式外侧的圆括号是可选的,但是写上去是一个好习惯。 (实现版本 Navigator 3.0 )

你可以使用 void 操作符指定超级链接。表达式会被计算但是不会在当前文档处装入任何内容。

下面的代码创建了一个超级链接,当用户点击以后不会发生任何事。当用户点击链接时,void(0) 计算为 0,但在 JavaScript 上没有任何效果。

<A HREF=”javascript:void(0)”>单击此处什么也不会发生</A>

下面的代码创建了一个超级链接,用户单击时会提交表单。

<A HREF=”javascript:void(document.form.submit())”>
单击此处提交表单</A>

对于jquery 和yui等前端框架来说他们都有阻止默认事件的方法,在调用window.location.href 等其他重定向方法之前阻止掉连接的默认事件就可以哈

比如

$(’#changesite-panel a.city’).click(function(ev){
ev.preventDefault();
changeSite($(this).attr(’rel’));
});
function changeSite(site){
window.location.href = ‘/event/index.php?from_city=’ + site;
}
})();