我在div上方有多个按钮,点击后使用
//jquery code
$("#conainerZero").hide();
$("#one-bt").click(function(){
$("#containerZero").load("file/anyfile.html");
$("#contanerZero").toggle();
}
<div id="contentContainer">
<button id="one-bt">first button</button>
<button id="two-bt">first button</button>
<button id="three-bt">Third button</button>
<hr>
<!--below is the div in which i want to use load content by jquery .load() method-->
<div id="containerZero"></div>
</div>
我的困境是当我点击一个不同的按钮将不同的内容加载到带有容器零的div的div时,然后返回单击第一个按钮我必须单击它两次才能得到它,我认为这是因为它是在我点击不同的按钮之前显示,然后回到相同的按钮。
答案 0 :(得分:1)
你需要做的事情
第一次:使用data
属性
第二次:如果您在css上使用containerZero
,则无需display:none
第三次:使用load
回调函数在完全加载后显示div
第4次:将您的代码包装在$(document).ready()
5th :为您的按钮添加一个类,以便在多次单击时不再运行该功能
第6次:对所有按钮使用相同的类,并为每个按钮ID制作一个click
,而不是使用三个click
所以你的代码应该是这样的
关于HTML
<div id="contentContainer">
<button id="one-bt" class="loadContent" data-url="file/anyfile1.html">first button</button>
<button id="two-bt" class="loadContent" data-url="file/anyfile2.html">Second button</button>
<button id="three-bt" class="loadContent" data-url="file/anyfile3.html">Third button</button>
<hr>
<!--below is the div in which i want to use load content by jquery .load() method-->
<div id="containerZero"></div>
</div>
关于CSS
#containerZero{
display : none;
}
On Js
$(document).ready(function(){
$(document).on('click' , '.loadContent:not(.active)' , function(){
var getfile = $(this).data('url');
$('.loadContent').removeClass('active');
$(this).addClass('active');
$("#containerZero").hide().load(getfile , function(){
$("#containerZero").slideDown();
});
});
});
这是演示确定我忽略了.load()
部分
$(document).ready(function(){
$(document).on('click' , '.loadContent:not(.active)' , function(){
var getfile = $(this).data('url');
$('.loadContent').removeClass('active');
$(this).addClass('active');
/*$("#containerZero").hide().load(getfile , function(){
$("#containerZero").slideDown();
});*/
// for test
$("#containerZero").hide().html(getfile);
$("#containerZero").slideDown();
});
$('.loadContent').eq(0).click();
});
&#13;
#containerZero{
display : none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contentContainer">
<button id="one-bt" class="loadContent" data-url="file/anyfile1.html">first button</button>
<button id="two-bt" class="loadContent" data-url="file/anyfile2.html">Second button</button>
<button id="three-bt" class="loadContent" data-url="file/anyfile3.html">Third button</button>
<hr>
<!--below is the div in which i want to use load content by jquery .load() method-->
<div id="containerZero"></div>
</div>
&#13;