我正在使用 Twitter Bootstrap 的按钮组在不同内容之间切换。一个例子可以在 http://jsfiddle.net/g8KSf/ 看到。
基本上,如果您单击“游戏”,games_container div 将出现,其他 div 将被隐藏。我已经工作得很好了。
我将帖子类型存储在数据库中,如帖子、游戏、视频等,并且我希望能够在页面加载时打开相关的 div,而不仅仅是单击。现在,当页面加载时,默认显示 post_container 。
假设我有一个 PHP 变量 $post_type = 'game';
,如何才能使 game_container 在页面加载时显示,同时仍然通过单击进行切换?
这是我到目前为止的js:
$('.container').hide();
$('#post_container').show();
$('.post_types button').click(function(){
var target = "#" + $(this).data("target");
$(".container").not(target).hide();
$(target).show();
$('#post_type').val($(this).text());
});
最佳答案
要在加载时显示游戏容器,您需要替换此行
$('#post_container').show();
到
$('#game_container').show();
目前您正在使用
$('#post_type').val($(this).text());
这里不要使用 this
来表示这一行 $(this).text()
,而是使用 target
变量,如下所示
$('#post_type').val($(target).text());
更新:
要在页面加载时动态显示,
将 post_type 的值存储在变量中
var ptype = ...存储帖子类型值...;
将值传递到此行
$('#'+ptype+'_container').show();
或
$('#'+$post_type+'_container').show();
关于javascript - 在页面加载和单击时显示/隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11798889/