javascript - 为什么缺少的函数参数的值为“[object Object]”?
问题描述
我有一个注册模式窗口,它应该在两种情况下出现:a)在网页上单击了一个按钮;b) 网页的 URL 中有“#modal”(例如 mydomain/mypage.html#modal)——在这种情况下,网页应该加载上面的模式窗口。
方案 A 的工作原理如下:
- html
<a href='#' class='button signup' data-target='.signup-modal'>Find out more</a>
- JS + 查询
$(function() {
$('.signup').on('click', showModal);
});
场景 B:
- JS
$(document).ready(function(){
var hash = window.location.hash;
if(hash === '#modal'){
showModal('.signup-modal');
}
});
该showModal
功能的工作原理如下:
function showModal(modalType) {
var getTarget = $(this).data('target');
if (!getTarget) {
var target = modalType;
} else {
var target = getTarget;
}
$(target).show();
return false;
}
这行得通。 但是,我之前对该功能的尝试略有不同:
function showModal(modalType) {
if (!modalType) {
var target = $(this).data('target');
} else {
var target = modalType;
}
$(target).show();
return false;
}
这不适用于场景 A。
我想,如果函数没有指定参数,它会得到modalType = undefined
,然后var target = $(this).data('target');
。我添加alert(target)
并发现,单击按钮后,我得到[object Object]
的值为target
.
谁能解释一下为什么?
解决方案
事件处理程序回调的第一个参数是事件对象。所以if (!modalType)
永远不会是真的。
您可以检查它是否是选择器版本的字符串。就像是:
if ( typeof modalType !== 'string' )
这是一个简化的示例:
function doStuff(thing){
if(!thing){
// won't get called in the two scenarios used
console.log('no thing');
return
}
if(typeof thing === 'string'){
console.log('Argument is string:', thing)
}else{
// thing is event object
const event = thing;
console.log('Event type:', event.type);
console.log('Target:', event.target)
// also `this` will be the element instance event occurred on
console.log('Tagname:', this.tagName);
}
}
$('button').on('click', doStuff);
doStuff('SomeString')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click me</button>
推荐阅读
- javascript - 如何实现 JavaScript getUserMedia 存根以发送自定义音频字节
- python - ValueError:信号仅在主线程中有效
- scala - 通过拆分提取字符串和符号
- sql - 是否可以通过将列与另一个存在的临时表匹配来更改列?
- python - Pandas + PyMongo:将 DataFrame 写入 MongoDB
- windows - 无法访问在 swarm 集群中运行的 docker 容器
- jquery - Kendo-Vue-Grid 刷新数据源时不丢失排序的方式?
- android - Firebase Push Notofication 同时生成 apk
- aws-lambda - 如何为 API Gateway Websocket 编写 Java Lambda 处理程序?
- multithreading - Hololens - Unity:LoadImage 冻结主线程