javascript - 使用 jQuery 实时显示隐藏自定义元框

标签 javascript jquery wordpress addclass removeclass

我正在尝试通过 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/

相关文章:

javascript - 在 Vue Client 3 中使用 webpack 插件

javascript - 有什么方法可以检测通过终端服务运行的浏览器?

javascript - 设置表单内隐藏输入的值

javascript - 当事件处理程序附加到父 HTML 元素时,如何防止默认事件操作?

jquery - "#orderedlist > li"选择器

javascript - AngularJS : angular-ui-router always redirects to $urlRouterProvider. 否则位置

javascript - 文本中包含 "mm/dd/yyyy"的日期格式

php - htaccess 301 重定向与 Wordpress 中的 php 脚本

php - Wordpress - 尝试编辑帖子 - "Fatal error: Out of memory"...但内存限制很高

html - wordpress 列中的 css 定位问题