JQuery показать/скрыть не работает
У меня есть базовая html-страница с некоторыми JS и CSS:
$('.expand').click(function() {
$('.img_display_content').show();
});
@charset "utf-8";
/* CSS Document */
.wrap {
margin-left: auto;
margin-right: auto;
width: 40%;
}
.img_display_header {
height: 20px;
background-color: #CCC;
display: block;
border: #333 solid 1px;
margin-bottom: 2px;
}
.expand {
float: right;
height: 100%;
padding-right: 5px;
cursor: pointer;
}
.img_display_content {
width: 100%;
height: 100px;
background-color: #0F3;
margin-top: -2px;
display: none;
}
<html>
<head>
<link href="beta.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<div class="wrap">
<div class="img_display_header">
<div class="expand">+</div>
</div>
<div class="img_display_content"></div>
</div>
</div>
</body>
</html>
Ответы
Ответ 1
Просто добавьте функцию готовности документа, таким образом она ждет, пока загрузится DOM, а также с помощью псевдонима :visible
вы можете написать простую функцию show and hide.
Пример
$(document).ready(function(){
$( '.expand' ).click(function() {
if($( '.img_display_content' ).is(":visible")){
$( '.img_display_content' ).hide();
} else{
$( '.img_display_content' ).show();
}
});
});
Ответ 2
Демо
$( '.expand' ).click(function() {
$( '.img_display_content' ).toggle();
});
.wrap {
margin-left:auto;
margin-right:auto;
width:40%;
}
.img_display_header {
height:20px;
background-color:#CCC;
display:block;
border:#333 solid 1px;
margin-bottom: 2px;
}
.expand {
float:right;
height: 100%;
padding-right:5px;
cursor:pointer;
}
.img_display_content {
width: 100%;
height:100px;
background-color:#0F3;
margin-top: -2px;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="img_display_header">
<div class="expand">+</div>
</div>
<div class="img_display_content"></div>
</div>
</div>
Ответ 3
Используйте этот
<script>
$(document).ready(function(){
$( '.expand' ).click(function() {
$( '.img_display_content' ).show();
});
});
</script>
Назначение события всегда после загрузки Document Object Model
Ответ 4
Содержимое еще не готово, вы можете переместить js в конец файла или сделать
<script>
$(function () {
$( '.expand' ).click(function() {
$( '.img_display_content' ).show();
});
});
Так, чтобы документ ожидал загрузки перед запуском.