我维护(但没有开发)在其博客页面上有评论表单的 ASP 站点。 添加评论时,页面会显示一个新的 div,样式为“comments-wrap”类。如果还没有评论,则该 div 根本不会出现。它不提供 ID,因为页面上最终可能会有多个评论。
我想向空页面添加一个新的 div(可能使用   或样式 display:none),除非脚本检测到“comments-wrap”类的存在。
例如,让我们调用新的 div 。我希望它始终出现在页面上(例如,),但是当在页面上检测到“comments-wrap”类时,空间会更改为“Previous Comments”。
到目前为止我有:
<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>
关于javascript检测div类的存在,如果为真,则更改不同div的innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851037/