简体   繁体   English

当另一个div为空时隐藏div

[英]Hide div when another div is empty

I know theres lots of answers on this problem, but I've read through all I can find but still cant get it to work. 我知道在这个问题上有很多答案,但是我已经阅读了所有可以找到的内容,但仍然无法正常工作。

I have a div which i need to be hidden if another div is empty, or just containing whitespace. 我有一个div,如果另一个div为空或仅包含空格,则需要将其隐藏。

<div id="rt-main" class="mb12">
    <div class="rt-grid-12">
        <div class="rt-block component-block main-overlay-light">
            <div id="rt-mainbody">
                <div class="component-content">
                    <div class="blog-featured"></div>

( I want to hide div.mb12 when div blog-featured = ' ' ) (当div blog-featured =''时我想隐藏div.mb12)

My closest bet is this: 我最接近的选择是:

$(document).ready(function() {
   str = $('div.section').text();
   if($.trim(str) === "") {
     $('div.section').hide();
   }
});

But I get all sorts of errors in the console when trying. 但是尝试时会在控制台中遇到各种错误。

Now I've got "TypeError: Cannot call method 'text' of null" 现在,我收到“ TypeError:无法调用方法'text'为null的信息”

On the actual site (not included in the question), you have this: 在实际站点(问题中未包括)上,您具有以下功能:

jQuery.noConflict();

This makes it so that $ is no longer jquery. 这使得$不再是jquery。 Most likely because one of the many other libraries you have included uses the $ name. 很可能是因为您包含的许多其他库之一使用$名称。 You can simply change your code to use jQuery in place of $ : 您只需更改代码即可使用jQuery代替$

jQuery(document).ready(function() { ...

Alternatively, you can assign jQuery to a different variable name: 另外,您可以将jQuery分配给其他变量名称:

var $j = jQuery.noConflict();

$j(document).ready(function(){ ...

You want this - 你要这个 -

jQuery(document).ready(function () {
    var str = jQuery('div.blog-featured').text();
    if (jQuery.trim(str) === "") {
        jQuery('div.mb12').hide();
    }
});

Demo ---> http://jsfiddle.net/PqXWJ/20/ 演示---> http://jsfiddle.net/PqXWJ/20/

Are you loading the jQuery library before your script? 您要在脚本之前加载jQuery库吗? Do you have something like this in the <head> tags of your page? 页面的<head>标记中是否有类似的内容?

    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    </head>

    <script type="text/javascript">
        $(document).ready(function() {
        etc etc
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM