【问题标题】:Can't get height of dynamic created button using jquery无法使用 jquery 获取动态创建按钮的高度
【发布时间】:2018-11-04 18:51:03
【问题描述】:

我有什么:

我动态创建一个按钮并尝试访问按钮宽度。在这个例子中,我正在做console.log(),但在我的实际情况中,我想将该值用于其他事情。

let deleteButton = $(document.createElement("button"))
  .addClass("deleteButton")
  .text("delete")
  .click(function() {
    delete(this);
  });

console.log($(deleteButton).width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

问题:

按钮默认有widthheight,但console.log() 显示为零。

如何获取按钮的默认宽度和高度?

观察:最有可能被接受的答案是使用类似 jquery 的 .width() 函数,或者解释为什么该函数不起作用并给出更好的解决方案。

【问题讨论】:

  • 能不能做个笔形文件分享一下

标签: javascript jquery button


【解决方案1】:

函数$.width() 获取匹配元素集中第一个元素的当前计算宽度。

基本上,该元素没有被引擎渲染/处理,因此width 在添加到 DOM 树之前不可用。

let deleteButton = $(document.createElement("button"))
  .addClass("deleteButton")
  .text("delete")
  .click(function() {
    delete(this);
  });

// Here the engine will render/process this element.
$(document.body).append(deleteButton);

console.log($(deleteButton).width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 2012-02-14
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2023-01-30
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多