【问题标题】:What is the correct way to refactor a jQuery replaceWith to an arrow function?将 jQuery replaceWith 重构为箭头函数的正确方法是什么?
【发布时间】:2020-01-17 16:12:25
【问题描述】:

这是当前的遗留代码

$('#container input[type="number"], #container input[type="text"]').replaceWith(function () {
    return $(`<p class="readonly" id="${$(this).prop('id')}">${$(this).val()}</p>`).append($(this).contents());
});

我需要进行一些清理和重构,并希望对其进行现代化改造,但 replaceWith 似乎没有参数可以用来在我们使用它的地方替换“this”,例如 $(这个).prop。我认为它应该是 event.currentTarget 但这不起作用(或者我的实现可能是错误的)

【问题讨论】:

  • 所以,第一个问题。为什么?如果您的逻辑是使用this 编写的,并且它有效,为什么要切换到箭头函数?箭头函数可以接受传递给它们的参数并使用它们。我只是有点困惑,为什么你要在它已经工作的时候对其进行重构。
  • 这能回答你的问题吗? Can you bind 'this' in an arrow function?
  • 我想重构它主要是因为样式的原因。我们的 linter 设置将其标记为“意外的 'this'

标签: jquery ecmascript-6


【解决方案1】:

replaceWith 似乎没有我可以用来替代“this”的参数

没有。

documentation 表明该函数没有传递任何参数。

箭头函数根本不适合在这里使用。从来没有设计为函数声明或表达式的通用替代品。

【讨论】:

  • jsfiddle.net/34fabqwL 从技术上讲,该方法被赋予了参数,但它们都不是被替换的元素。
【解决方案2】:

你能用箭头函数做到这一点吗?是的。您提供 replaceWith 的方法没有提供您要替换的元素,但它确实为您提供了索引。因此,考虑到这一点,如果您只是出于任何原因必须使用箭头函数,则可以使用该索引来获取您的元素。

const $inputs = $('input');

$inputs.replaceWith( index => {
  let input = $inputs[ index ];
  
  return `<p class="readonly" id="${input.id}">${input.value}</p>`;
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1" value="Value 1">
<input type="text" id="input2" value="Value 2">
<input type="text" id="input3" value="Value 3">

我个人认为,这种情况下切换到箭头功能没有多大意义,但可以做到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    相关资源
    最近更新 更多