我有一个包含三个 div(标题、内容和一个虚拟 div)的小型控制面板。在该面板上方我有一个按钮,单击该按钮必须隐藏和显示内容。
我的目标是当我单击按钮以更改内容 div 的 id(当它隐藏时和显示时),按钮也必须从关闭更改为打开。在这个阶段,我让内容出现和消失,但它被窃听了。我想我必须使用 stopPropegation 但我不知道如何。如果你能修好它,我会很高兴。提前致谢。
html代码:
<!DOCTYPE html>
<html>
<head>
<title>Control Panel</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="collapseExpand.js"></script>
</head>
<body>
<div id="button">
<a href="javascript:void(0);" onclick="return hideShowContent()">Close</a>
</div>
<div class="wrapper">
<h1>Title</h1>
<div id="content"> "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</div>
</div>
<div id="dummyDiv">
test division
</div>
</body>
</html>
CSS 代码:
html, body {
height: 100%;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
}
#button{
margin-bottom: 10px;
}
h1{
margin-left: 10px;
margin-right: 10px;
border-bottom: 1px solid gray;
}
.wrapper{
border: 1px solid gray;
width: 430px;
}
#content, #contentHide{
margin: 10px;
}
#dummyDiv{
margin-top: 10px;
font-weight: bold;
font-size: 1.2em;
}
JavaScript 代码:
function hideShowContent() {
console.log('The button was clicked');
$(document).ready(function() {
$('#button').click(function() {
$("#content").attr('id', 'contentHide');
$('#contentHide').hide(500);
});
});
$(document).ready(function() {
$('#button').click(function() {
$("#contentHide").attr('id', 'content');
$('#content').show(500);
});
});
}
JSfiddle:http://jsfiddle.net/wvLfbfgh/
最佳答案
我已经修复了你的脚本,你只需要:
$(document).ready(function() {
$('#button').click(function() {
$("#content").toggle(500);
});
});
http://jsfiddle.net/wvLfbfgh/1/
基本上,您创建了函数并将其绑定(bind)到 onclick="return hideShowContent()
并且该函数在每次点击时额外绑定(bind)了新事件。这是错误的,只在 $(document) 中定义.ready
你的 Action 。不要使用隐藏/显示,而是使用 toggle
自动检测目标是显示还是隐藏
关于javascript - 如何正确触发onClick事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25383720/