简体   繁体   English

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

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

I maintain (but didn't develop) ASP site that has a comments form on its blog pages. 我维护(但未开发)ASP网站,该网站的博客页面上有评论表格。 When a comment is added, the page shows a new div styled with the class "comments-wrap". 添加注释后,页面将显示一个新的div样式,其样式为“ comments-wrap”类。 If there is no comments yet, that div won't appear at all. 如果尚无任何评论,该div根本不会出现。 It doesn't us an ID because there may end up being multiple comments on the page. 它不是我们的ID,因为页面上可能会出现多个注释。

I want to add a new div to the page(s) that is empty (maybe using a &nbsp or the style display:none) unless the a script detects the presence of the "comments-wrap" class. 除非脚本检测到“ comments-wrap”类的存在,否则我想向空白的页面添加一个新的div(也许使用&nbsp或样式display:none)。

For example's sake, lets call the new div . 例如,让我们调用新的div。 I'd like it to be present on the page all of the time (eg. ), but the space changes to "Previous Comments" when the "comments-wrap" class is detected on the page. 我希望它可以一直显示在页面上(例如),但是当在页面上检测到“ comments-wrap”类时,该空间将变为“以前的评论”。

So far I have: 到目前为止,我有:

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

If you are using jquery use .length to find the number of elements currently matched 如果您使用的是jquery,请使用.length查找当前匹配的元素数

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

Edit 编辑

<!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