获取页面上所有div id的高度

时间:2016-05-23 17:45:04

标签: javascript jquery

我正在尝试找到一种方法,在发送到打印机之前,如果任何div大于预设尺寸,则向自己发送警报。

每个页面都不同,并且有不同的div id用于样本测试问题。

此外,每个div的高度不会像这里那样预先设定。 目前,我有这个,但它没有像我希望的那样工作:

<style>
#one{background:#ddd;height:250px;}
#two{background:#000;height:300px;}
</style>
<div id="page">
  <div id="one">
    stuff
  </div>
  <div id="two">
    more stuff
  </div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
  var IDs = $("#page div[id]")         
  .map(function() { return this.id; })
  var result = $(this.id).height();
  if(result > 275){
    alert("over");
  }else{
    alert("under");
  }
</script>

我觉得我很亲近。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您不需要id,但如果您想将搜索限制为id s的div,则表明您已正确完成此操作。当您尝试使用结果时,问题就出现了。

您希望遍历匹配元素集。 jQuery提供each来做到这一点:

$("#page div[id]").each(function() {
    // This is called once for each matching div;
    // `this` refers to each of the divs. So:
    if ($(this).height() > 275) {
        alert(this.id " is over");
    } else {
        alert(this.id + " is under");
    }
});