在函数参数中使用变量,无论是否使用Jquery

Using variables in function parameters, with or without Jquery

本文关键字:是否 Jquery 变量 函数 参数      更新时间:2023-09-26

我想写一个可以与不同元素重用的函数。

其想法是获取窗口高度并将其应用于不同的元素。

我以为我可以做这样的事情,但它不起作用:

function autoHeight(element) {
  var height = window.innerHeight;
  $(element).css('height', height);
}
autoHeight('.dashboard-sidebar');
autoHeight('.some-element');

它不起作用。我知道我很接近,但我错过了什么!

提前感谢!

这里似乎运行良好:https://jsfiddle.net/gerLe2x9/

您是否已将JS封装在$(window).load:中

$(window).load(function() {
    function autoHeight(element) {
       var height = window.innerHeight;
       $(element).css('height', height);
    }
    autoHeight('.dashboard-sidebar');
    autoHeight('.some-element');
}

使用JavaScript

function autoHeight(element) {
  var height = window.innerHeight;
  var ele = document.querySelector(element);
  if (ele) {
    ele.style.height = height + 'px';
  }
}
autoHeight('.dashboard-sidebar');
autoHeight('.some-element');
div {
  width: 120px;
  height: 120px;
  background: #DDDDDD;
  margin: 5px;
  display: inline-block;
}
<div class="dashboard-sidebar"></div>
<div class="some-element"></div>