javascript - 如果函数只有一个参数,向函数添加可选参数的正确方法是什么?
问题描述
我有一个函数,我需要在 onClick 操作和代码的其他部分中使用它。我正在尝试创建一个可选参数。可选参数返回一个类对象而不是 false 值。
import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
.html('Click me') // Try edit it...
.on('click', test)
返回:
{
originalEvent:[object PointerEvent],
type:"click",
isDefaultPrevented:f returnFalse {...},
target:<button class="btn btn-warning m-auto"></button>,
currentTarget:<button class="btn btn-warning m-auto"></button>,
relatedTarget:null,
timeStamp:2798.800000000745,
jQuery36007002776368131782:true,
delegateTarget:<button class="btn btn-warning m-auto"></button>,
handleObj: {...},
data:undefined
}```
解决方案
问题是通过将函数按jQuery#on()
原样传递,它将接收on
传递给它的所有参数。
就像这样做:
// vvvvvvv----------vvvvvvv--- Get all arguments that `on` passes and pass them to `test`
.on('click', (...args) => test(...args))
并且,jQuery#on()
确实将参数传递给您的函数,即事件对象,因此它不会回退到使用默认值。
如果你想避免这种情况,你可以在你的函数周围创建一个匿名包装器,它不会将参数转发到test
:
import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
.html('Click me')
// vv--- Pass nothing in here
.on('click', () => test())
推荐阅读
- sql - SQL Server 2017 中的 CTE 递归
- javascript - 有没有办法使用 Handlebars.js 使用 jQuery 注入模板?
- terraform - snowflake_table 使用 Terraform 添加列级注释
- sql - 在 SQL 中的每个循环之后添加组 ID
- swift - 快速的firebase搜索用户结果
- c++ - 我可以将向下转换应用于迭代器吗?
- docker - numpy 的 Docker 安装失败 - miniconda
- marklogic - roxy 转换为 ml-gradle 属性错误
- java - SQL 语法错误:您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册
- flutter - Dart Flutter DevTools“调试器”选项卡未显示