使用 jQuery 覆盖 JavaScript 中的复选框 [英] Overriding check box in JavaScript with jQuery
问题描述
帮助处理单元测试复选框行为.我有这个页面:
Help with unit testing checkbox behavior. I have this page:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function() {
$('<div><input type="checkbox" name="makeHidden" id="makeHidden" checked="checked" />Make Hidden</div>').appendTo('body');
$('<div id="displayer" style="display:none;">Was Hidden</div>').appendTo('body');
$('#makeHidden').click(function() {
var isChecked = $(this).is(':checked');
if (isChecked) {
$('#displayer').hide();
}
else {
$('#displayer').show();
}
return false;
});
});
</script>
</head>
<body>
</body>
</html>
这不起作用,因为点击处理程序中的 return false;
.如果我删除它,效果很好.问题是,如果我将点击函数拉出到它自己的函数中并使用 qunit 对其进行单元测试,它不会在没有 return false;
This doesn't work it is because of the return false;
in the click handler. If I remove it it works great. The problem is if I pull the click function out into it's own function and unit test it with qunit it will not work without the return false;
使用@patrick 的回答,我的结果是:
Using @patrick's answer my results are:
火狐:
- 玩具的手动测试 - 很好.
- 单元测试 - 很好.
- 生产应用的手动测试 - 很好.
Internet Explorer:
Internet Explorer:
- 玩具的手动测试 - 失败.
- 单元测试 - 很好.
- 生产应用的手动测试 - 失败.
Internet Explorer 最初需要一键式.之后需要点击两次.
我认为 jQuery 是为了抽象出浏览器?
I thought jQuery is to abstract away browsers?
对于解决方案,我是否必须覆盖整个复选框行为?
Am I going to have to override the entire check box behavior for a solution?
在我的单元测试中,这是我对用户进行复选框模拟的方式:
In my unit tests this is how I am doing the check box simulation of a user:
$(':input[name=shipToNotActive]').removeAttr('checked');
$('#shipToNotActive').change();
还有:
$(':input[name=shipToNotActive]').attr('checked', 'checked');
$('#shipToNotActive').change();
推荐答案
用change
代替click
怎么样?
$('#makeHidden').change(function() {
var isChecked = $(this).is(':checked');
if (isChecked) {
$('#displayer').hide();
}
else {
$('#displayer').show();
}
return false;
});
return false;
不会妨碍,因为该事件是由于发生更改而触发的.
The return false;
won't be in the way since the event is fired as a result of the change having occurred.
这篇关于使用 jQuery 覆盖 JavaScript 中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!