简体   繁体   English

TypeScript each() 作为箭头函数

[英]TypeScript each() as an Arrow function

I have the following TypeScript function:我有以下打字稿功能:

$.each($("[data-static-map-image]"), function () {
    $(this).attr("src", $(this).data("mapImageUrl"));
});

I would like to convert this into an Arrow function.我想将其转换为箭头函数。 Unfortunately, I can't figure out how to make it work with the each loop.不幸的是,我不知道如何使它与每个循环一起工作。 Can someone give me a hint?有人可以给我一个提示吗?

PS I ask for your indulgence as I am still in the beginning of the learning phase. PS我还处于学习阶段的开始,请您放纵一下。

The jQuery documentation on jQuery.each explains that the callback gets arguments: jQuery.each上的 jQuery 文档解释了回调获取参数:

callback打回来
Type: Function( Integer indexInArray, Object value )类型:函数(整数 indexInArray,对象值)
The function that will be executed on every value.将对每个值执行的函数。

So if you really want to stick with jQuery, then make use of the arguments passed to the callback function:因此,如果您真的想坚持使用 jQuery,请使用传递给回调函数的参数:

$.each($("[data-static-map-image]"), (i, elem) => {
    $(elem).attr("src", $(elem).data("mapImageUrl"));
});

You can do this in plain JavaScript (and TypeScript too)您可以使用纯 JavaScript(也可以使用 TypeScript)来执行此操作

Use querySelectorAll to get all elements matching your selector and then use the Array#forEach function:使用querySelectorAll来获取与您的选择器匹配的所有元素,然后使用Array#forEach函数:

const allElements = Array.from(document.querySelectorAll('[data-static-map-image]'))

allElements.forEach(element => {
  const url = element.getAttribute('data-mapImageUrl')
  element.setAttribute('src', url)
})

The main reason you cannot use an arrow function in your context is because this refers to the outer scope as opposed when using anonymous functions which have their own this which jQuery is going to bind to each of the elements您不能在上下文中使用箭头函数的主要原因是因为this指的是外部范围,而不是使用匿名函数时,这些函数有自己的this jQuery 将绑定到每个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM