Javascript 为什么某些jquery代码只有在';在我的html正文部分的末尾是什么?
我有以下创建选项卡的代码。它在html正文部分的末尾起作用,但如果我将它放在开头——在定义所有div之前,它就不起作用了。为什么会这样Javascript 为什么某些jquery代码只有在';在我的html正文部分的末尾是什么?,javascript,jquery,document,position,Javascript,Jquery,Document,Position,我有以下创建选项卡的代码。它在html正文部分的末尾起作用,但如果我将它放在开头——在定义所有div之前,它就不起作用了。为什么会这样 <script type="text/javascript"> $("ul.tabs li.label").hide(); $("#tab-set > div").hide(); $("#tab-set > div").eq(0).show(); $("ul.tabs a").click( functi
<script type="text/javascript">
$("ul.tabs li.label").hide();
$("#tab-set > div").hide();
$("#tab-set > div").eq(0).show();
$("ul.tabs a").click(
function() {
$("ul.tabs a.selected").removeClass('selected');
$("#tab-set > div").hide();
$(""+$(this).attr("href")).show();
$(this).addClass('selected');
return false;
}
);
$("#toggle-label").click( function() {
$(".tabs li.label").toggle();
return false;
});
</script>
$(“ul.tabs li.label”).hide();
$(“#选项卡集>div”).hide();
$(“#选项卡集>div”).eq(0.show();
$(“ul.a”)。单击(
函数(){
$(“ul.tabs a.selected”).removeClass(“selected”);
$(“#选项卡集>div”).hide();
$(“”+$(this.attr(“href”).show();
$(this.addClass('selected');
返回false;
}
);
$(“#切换标签”)。单击(函数(){
$(“.tabs li.label”).toggle();
返回false;
});
这很可能是因为DOM还没有准备好,因此它们不存在
因此,您需要执行以下操作:
$(function() {
// Any code in here will only be executed when the DOM is ready.
});
你需要用一个文档就绪块来包装它。这将防止在页面完全加载之前触发代码
<script type="text/javascript">
$(function() {
// do something on document ready
$("ul.tabs li.label").hide();
$("#tab-set > div").hide();
$("#tab-set > div").eq(0).show();
$("ul.tabs a").click(
function() {
$("ul.tabs a.selected").removeClass('selected');
$("#tab-set > div").hide();
$(""+$(this).attr("href")).show();
$(this).addClass('selected');
return false;
}
);
$("#toggle-label").click( function() {
$(".tabs li.label").toggle();
return false;
});
});
</script>
$(函数(){
//在文档上做一些准备工作
$(“ul.tabs li.label”).hide();
$(“#选项卡集>div”).hide();
$(“#选项卡集>div”).eq(0.show();
$(“ul.a”)。单击(
函数(){
$(“ul.tabs a.selected”).removeClass(“selected”);
$(“#选项卡集>div”).hide();
$(“”+$(this.attr(“href”).show();
$(this.addClass('selected');
返回false;
}
);
$(“#切换标签”)。单击(函数(){
$(“.tabs li.label”).toggle();
返回false;
});
});
“…在定义所有div之前”应该给你一个线索-如果它们还没有定义,你的代码怎么可能操纵它们?@coward:这不可靠。它并不总是有效的,在每个浏览器中,这基本上是学习jQuery的第一件事。
jQuery(function($) {
// put your code in here and it will be executed
// when the document has fully loaded.
});