【问题标题】:using arrow function on Jquery function在 Jquery 函数上使用箭头函数
【发布时间】:2018-04-17 13:42:34
【问题描述】:

很难将 Jquery 地图函数转换为箭头函数。

这里是fiddle。

// find elements
$('button').click(function(e) {
  let answerArray = $(`[name="foo"]`).map(function() {
    return $(this).val();
  }).get();
  console.log(answerArray)
  
  let answerArray2 = $(`[name="foo"]`).map(x => $(x).val()).get();
  console.log(answerArray2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="foo">
<input name="foo">
<button>
  enter
</button>

但我收到了。

VM118 jquery.js:7977 Uncaught TypeError: Cannot read property 未定义的“toLowerCase” 在 jQuery.fn.init.val (VM102 jquery.js:7977) 在 HTMLInputElement.$.map.x ((index):74) 在 VM102 jquery.js:194 在 Function.map (VM102 jquery.js:443) 在 jQuery.fn.init.map (VM102 jquery.js:193) 在 HTMLButtonElement。 ((指数):74) 在 HTMLButtonElement.dispatch (VM102 jquery.js:5183) 在 HTMLButtonElement.elemData.handle (VM102 jquery.js:4991)

【问题讨论】:

  • Array.from($('[name="foo"]'), x =&gt; x.value)

标签: javascript jquery ecmascript-6 arrow-functions


【解决方案1】:

根据您的代码 x 指的是索引 not 元素,因此您会收到错误消息。

使用正确的callback 函数参数.map()。

类型:函数(整数 index,元素 domElement)=> 对象 将为当前集合中的每个元素调用的函数对象。

// find elements
$('button').click(function(e) {

  let answerArray2 = $(`[name="foo"]`).map((i, x) => $(x).val()).get();
  console.log(answerArray2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="foo">
<input name="foo">
<button>
  enter
</button>

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2016-08-06
    • 2015-12-29
    • 2018-08-02
    相关资源
    最近更新 更多