如果Jquery变量等于div的类,则将display设置为block

时间:2015-10-29 11:43:55

标签: php jquery

我使用php输出几个div - 每个div都有一个不同的国家/地区名称。

我还使用jquery输出变量,该变量检查div的内容是否已更改。该变量也将是国家名称。

如果jquery变量与div类匹配,我希望div为.show(),我该怎么做?

这是我(可怕)的尝试:

(function($) {
    $(document).ready(function () {
        $("#block1").bind("DOMSubtreeModified", function() {
            message = $("#block1").html();
            regiondiv = '.';
            fullregion = regiondiv + message;
            alert(fullregion);

            if ($('.region-logos').hasClass(message)) {
                $(fullregion).show();
            } else {
                $(fullregion).hide();   
            }

        });
    });                             
})(jQuery);

如果我点击加拿大,它会显示.Canada div,但如果我点击西班牙后,它会显示.Spain div以及{{ 1}} div。即,一旦您点击多个,它就会继续显示所有内容。如果您没有点击它,它不会隐藏div。

3 个答案:

答案 0 :(得分:1)

var class = 'no-class';     
$(document).ready(function () {
    $("#block1").bind("DOMSubtreeModified", function() {
       var regiondiv = '.';
       var fullregion = regiondiv + class ;
       $(".fullregion").hide();
       class = $("#block1").html();
       fullregion = regiondiv + class ;
       $(".fullregion").show();
    });   
}); 

答案 1 :(得分:0)

不确定我是否正确地遵循了这个问题。我假设您想要显示div,如果该div的类与javascript中的变量匹配。如果是这样,你可以试试这个:

(function($) {
    $(document).ready(function () {
        $("body").bind("DOMSubtreeModified", function() {
            // Not sure how are you generating this jquery variable
            var yourJqueryVariable;
            // Check if class name exists
            if ($(".yourJqueryVariable")[0]){
               $(".yourJqueryVariable").show(); //or even $(".yourJqueryVariable").css('display','block');
            }
        });
    });
})(jQuery);

答案 2 :(得分:0)

(function($) {
    $(document).ready(function () {
        $("#block1").bind("DOMSubtreeModified", function() {
            var message = $("#block1").html();

            //ok so you have the variable to check 
            if($('.'+message).length > )) { //is there 1 or more of these classes in the DOM?
                $('.'+message).each(function() { //there is, loop and show them all 
                    $(this).show();  
                }); 
            }

        });
    });
})(jQuery);

修改

好的,看看你的更新答案,假设有多个.region-logos,你需要在其中循环执行你的if:

$('.region-logos').each(function() {
    if($(this).hasClass(message)) {
       $(fullregion).show();
    }else {
       $(fullregion).hide();
    } 
});