【发布时间】:2012-09-30 22:39:56
【问题描述】:
我的 jQuery 代码没有按预期工作。
这是 HTML:
<a href="">Some link</a>
<br/>
<a class="delete_file_initial" href="">Delete file</a>
<span class="delete_file_question hide">are you sure to delete?</span>
<a class="delete_file_question confirm hide" href="http://example.com/delete">yes</a>
<a class="delete_file_question cancel hide" href="">no</a>
<br/>
<a class="move_file_initial" href="">Move file</a>
<span class="move_file_question hide">are you sure to move?</span>
<a class="move_file_question confirm hide" href="http://example.com/move">yes</a>
<a class="move_file_question cancel hide" href="">no</a>
还有 Javascript:
$(function() {
// delete file
$("a.delete_file_initial").click(function(event) {
event.preventDefault()
$(this).hide()
$(".delete_file_question").show()
});
$("a.delete_file_question").click(function(event) {
if ($(this).hasClass("cancel")) {
event.preventDefault()
$(".delete_file_question").hide()
$(".delete_file_initial").show()
}
});
// move file
$("a.move_file_initial").click(function(event) {
event.preventDefault()
$(this).hide()
$(".move_file_question").show()
});
$("a.move_file_question").click(function(event) {
if ($(this).hasClass("cancel")) {
event.preventDefault()
$(".move_file_question").hide()
$(".move_file_initial").show()
}
});
});
有两个类似的代码块:删除和移动。除了要加载的实际 URL 不同之外,它们应该做同样的事情。 预期行为如下。用户单击“删除”/“移动”链接,然后显示确认链接,他确认或取消操作。
问题是当我点击链接“delete_file_initial”时,它会隐藏,但链接“delete_file_question”不显示,留下一个空行。 “移动”块按预期工作。如果我评论“移动”块,“删除”块开始按预期工作。更奇怪的是,这个bug出现在谷歌Chrome 22.0.1229.79中,但在Firefox 15.0.1中一切正常。
如何修复这个错误?
【问题讨论】:
-
Chrome v.22 没有给我任何问题:jsfiddle.net/mblase75/cg8Sh -- 您在控制台中有任何错误吗?一个想法:
href属性永远不应该为空; use#orjavascript:as an "empty href" when needed.(始终以分号结束 JavaScript 行也是一个好习惯。) -
感谢您的评论。不,我在控制台中没有任何错误(即使在将有问题的
<br/>添加到 html 之后,请参阅我的答案)。会不会是一个 jquery 错误(我使用的是 1.4.4)?