【问题标题】:javascript to detect presence of div class and change innerHTML of a different div if truejavascript检测是否存在div类并更改不同div的innerHTML(如果为真)
【发布时间】:2012-10-02 19:04:57
【问题描述】:

我维护(但没有开发)在其博客页面上有一个 cmets 表单的 ASP 站点。 添加评论后,页面会显示一个新的 div,其样式为“cmets-wrap”类。如果还没有 cmets,则该 div 根本不会出现。它不需要我们的 ID,因为页面上可能最终有多个 cmets。

除非脚本检测到“cmets-wrap”类的存在,否则我想将新的 div 添加到空页面(可能使用 &nbsp 或样式 display:none)。

例如,让我们调用新的 div 。我希望它始终出现在页面上(例如),但是当页面上检测到“cmets-wrap”类时,空间会变为“Previous Comments”。

到目前为止,我有:

<script>
function myFunction() {
if ($(".comments-wrap")[0]) { 
document.getElementById("comments-previous").innerHTML="Previous Comments";
}
}
}
</script> 

【问题讨论】:

    标签: javascript html css if-statement


    【解决方案1】:

    如果您使用 jquery,请使用 .length 查找当前匹配的元素数

    <script>
       $(document).ready(function(){
           if ($(".comments-wrap").length) { 
              $("#comments-previous").html('Previous Comments');
           }
       });
    </script> 
    

    编辑

    <!DOCTYPE html>
    <html>
    <head>
    <title>Untitled</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    
    <script>
    $(document).ready(function(){
        if ($(".comments-wrap").length) { 
            $("#comments-previous").html('Previous Comments');
        }
    });
    </script> 
    </head>
    <body>
     <div class="comments-wrap"></div>
     <div id="comments-previous"></div>
    </body>
    </html>
    

    【讨论】:

    • 我注意到开发人员在头脑中调用
    • 是的。您必须使用 jquery 库文件。
    • 测试 html 是:
    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2016-10-27
    相关资源
    最近更新 更多