javascript - 有没有办法将 $this 从 jquery 转换为 javascript?
问题描述
最近在stackoverflow上摆弄了这个问题:
但是这个解决方案包括 jquery 和 $(this) 关键字。我想转换这段代码:
function distributeFields(deg) {
deg = deg || 0;
var radius = 200;
var fields = $('.field'), container = $('#container'),
width = container.width(), height = container.height(),
angle = deg || Math.PI*3.5, step = (2*Math.PI) / fields.length;
fields.each(function() {
var x = Math.round(width/2 + radius * Math.cos(angle) - $(this).width()/2);
var y = Math.round(height/2 + radius * Math.sin(angle) - $(this).height()/2);
if(window.console) {
console.log($(this).text(), x, y);
}
$(this).css({
left: x + 'px',
top: y + 'px'
});
angle += step;
});
}
这是我在陷入 ($this) 关键字之前尝试做的事情:
function distributeFieldsJS(deg){
deg = deg || 0;
let radius = 200;
let fields = document.querySelectorAll('.field'),
container = document.querySelector('#container'),
width = container.width(), height = container.height(),
angle = deg || Math.PI * 3.5,
step = (2*Math.PI) / fields.length;
})
解决方案
它在 jQueryeach
回调中,所以它指的是当前被迭代的元素,所以你只需要做
for (const field of fields) {
// refer to `field` here
}
并且field
将是本机 DOM 元素。(就像$(this)
引用 jQuery 中包装的相同元素一样)。
getBoundingClientRect会给你它的尺寸。
field.textContent
将检索其文本。field.style
将为您提供元素的CSSStyleDeclaration。
推荐阅读
- python - 大熊猫每个类别的计算
- java - nullpointexception:将数据插入firebase数据库时出错
- android - 本地化在 Marshmallow 及以下版本中不起作用
- c# - 如何在 Serenity MVC 框架上创建 TAB
- javascript - 将道具传递给子组件时如何避免未知道具错误?
- javascript - 过滤2个数组在相等时不返回空
- vba - 尽管检查为 FALSE 且 [value_if_false] 为 0 或 1,但 IF 语句错误
- sql-server - SQL Server 的虚拟服务器和物理存储
- python - 如何使用 OR 条件合并两个 pandas 数据框
- javascript - 正则表达式删除数字和其他字符