繁体   English   中英

javascript以检测div类的存在并更改其他div的innerHTML(如果为true)

[英]javascript to detect presence of div class and change innerHTML of a different div if true

我维护(但未开发)ASP网站,该网站的博客页面上有评论表格。 添加注释后,页面将显示一个新的div样式,其样式为“ comments-wrap”类。 如果尚无任何评论,该div根本不会出现。 它不是我们的ID,因为页面上可能会出现多个注释。

除非脚本检测到“ comments-wrap”类的存在,否则我想向空白的页面添加一个新的div(也许使用&nbsp或样式display:none)。

例如,让我们调用新的div。 我希望它可以一直显示在页面上(例如),但是当在页面上检测到“ comments-wrap”类时,该空间将变为“以前的评论”。

到目前为止,我有:

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

如果您使用的是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>

暂无
暂无

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

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