【问题标题】:This piece of javascript code is working in chrome but not in firefox这段 javascript 代码在 chrome 中工作,但在 Firefox 中没有
【发布时间】:2016-02-26 12:42:05
【问题描述】:
我使用 Jquery 和 Javascript 创建了一个计算器,在 Chrome 中一切正常,但在 Firefox 中却不行。
function validate(x, y, z) {
if ((isNaN(x) || x == "") || (isNaN(y) || y == "")) {
return "Please Enter A Valid Number";
} else if (z == "/" && y == 0) {
return "Divide By zero error";
} else if (event.keyCode == 32) {
return false;
} else {
return calculation(x, y, z);
}
}
Demo Here
【问题讨论】:
标签:
javascript
jquery
google-chrome
firefox
cross-browser
【解决方案1】:
不要依赖window.event。这是一种并非所有浏览器都实现的微软主义。但是,每个处理程序都会将事件作为参数接收。明确使用它:
$(document).ready(function() {
$("#first").focus();
$('#first,#second,#oper').keyup(function(evt) {
// HERE ^^^
$('#demo').html(validate(evt.keyCode, $('#first').val(), $('#second').val(), $('#oper').val()));
// and HERE ^^^^^^^^^^^
});
});
function validate(key, x, y, z) {
// and HERE ^^^
if ((isNaN(x) || x == "") || (isNaN(y) || y == "")) {
return "Please Enter A Valid Number";
} else if (z == "/" && y == 0) {
return "Divide By zero error";
} else if (key == 32) {
return false;
} else {
return calculation(x, y, z);
}
}
【解决方案2】:
link
$(document).ready(function() {
$("#first").focus();
$('#first,#second,#oper').keyup(function(event) {
$('#demo').html(validate(event,$('#first').val(), $('#second').val(), $('#oper').val()));
});
});
function validate(event,x, y, z) {
if ((isNaN(x) || x == "") || (isNaN(y) || y == "")) {
return "Please Enter A Valid Number";
} else if (z == "/" && y == 0) {
return "Divide By zero error";
} else if (event.keyCode == 32) {
return false;
} else {
return calculation(x, y, z);
}
}