我正在尝试通过 jQuery 切换一些自定义元框的可见性。 我设法默认隐藏它们,并在单击正确的帖子格式时使它们可见。
我没有找到在用户更改帖子格式时使元框消失的解决方案。
例如 默认:隐藏 点击“旁白”:显示 从“旁白”切换到任何其他帖子格式:隐藏。
我有以下代码:
jQuery(document).ready(function () {
jQuery("#postbox-container-2").addClass("hidden");
if (jQuery("input#post-format-video").is(':checked')) {
jQuery("#postbox-container-2").removeClass("hidden");
}
jQuery("input#post-format-video").change(function () {
if (jQuery(this).is(':checked')) {
jQuery("#postbox-container-2").removeClass("hidden");
}
});
});
有什么想法吗?
基于@zipp fiddle的不同方法
Query(document).ready(function() {
jQuery( "#postbox-container-2" ).hide();
var toToggle='';
jQuery('input#post-format-video').change(function() {
if (toToggle){
jQuery(toToggle).hide();
}
//alert(this.value+ " is checked");
var selector='#postbox-container-2';
jQuery(selector).toggle();
toToggle=selector;
});
});
即使这个工作正常,但当我单击不同的单选按钮时也不会改变
最佳答案
这是一个jsfiddle以你的例子。触发更改事件only on the checked input 。当未选中特定输入时,不会触发它。为了知道您的特定输入是否未选中,您需要测试所选输入是否是您的: $(this).attr('id') == 'post-format-video'
并执行你的行动。在我的示例中,我使用 $('input:radio[name=myRadio]')
选择 radio 输入,因此您需要调整 html 和代码以获得正确的选择器。
//This selector is triggered when my radio is selected for all input radio that I want to listen to
$('input:radio[name=myRadio]').change(function() {
//if we have a radio button selected previously we hide the div related
if (toToggle){
$(toToggle).hide();
}
//select the div we want to show
var selector;
if ($(this).attr('id')=='post-format-video'){
selector='#postbox-container-2';
}
...
//show it (could have called toggle() )
$(selector).show();
//store it for the next selection
toToggle=selector;
关于javascript - 使用 jQuery 实时显示隐藏自定义元框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25344982/