问题
I use this code to run a slide toggle but it doesn't open when I click on it:
JS Code:
<script type="text/javascript">
$(document).ready(function () {
alert('hi i came to toggle');
$(".flip").click(function () {
$(this).next().slideToggle("fast");
});
});
function ViewGetSubjects(data) {
var subjects = (typeof data) == 'string' ? eval('(' + data + ')') : data;
$('#subjects').empty();
for (var i = 0; i < subjects.length; i++)
{
$('#subjects').append('<h1 class = "flip">'+subjects[i].Wkp_lesson+'</h1><div class="panel" >' + ' Weekly Body: ' + subjects[i].Wkp_Body + ' Weekly Body: ' + subjects[i].Wkp_Body + ' Weekly Lesson: ' + subjects[i].Wkp_lesson + '</div>');
}
}
CSS:
div.panel,h1.flip
{
margin:0px;
padding:5px;
text-align:center;
background:#488AC7;
border:solid 1px #F6358A;
}
div.panel
{
height:120px;
display:none;
}
Do you know why?
Thanks a lot :)
回答1:
If you are not using latest version of jquery
$(".flip").live('click', function(e){
$(this).next().slideToggle("fast");
});
otherwise it should be
$("#subjects").on('click', 'h1.flip', function(e){
$(this).next().slideToggle("fast");
});
because you are appending DOM
(h1
with class name flip
) elements dynamically inside the #subjects
(element that has id=subjects) element.
References : on and live (deprecated).
回答2:
Apart from my comment, did you possibly forget to include the jquery library?
<script src="http://code.jquery.com/jquery-latest.js"></script>
This will include the latest version directly from jquery.com, although it is suggested that you copy the code and save it in your own file.
来源:https://stackoverflow.com/questions/10059030/slide-toggle-jquery-function-not-working