gpt4 book ai didi

javascript - 无法使用jquery获取动态创建按钮的高度

转载 作者:行者123 更新时间:2023-11-30 14:18:31 25 4
gpt4 key购买 nike

我有什么:

我动态创建一个按钮并尝试访问按钮宽度。在这个例子中,我正在做 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() 或解释为什么该函数不起作用并展示更好的解决方案。

最佳答案

$.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>

关于javascript - 无法使用jquery获取动态创建按钮的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com