首页 > 解决方案 > 为什么缺少的函数参数的值为“[object Object]”?

问题描述

我有一个注册模式窗口,它应该在两种情况下出现:a)在网页上单击了一个按钮;b) 网页的 URL 中有“#modal”(例如 mydomain/mypage.html#modal)——在这种情况下,网页应该加载上面的模式窗口。

方案 A 的工作原理如下:

    <a href='#' class='button signup' data-target='.signup-modal'>Find out more</a>
$(function() {
    $('.signup').on('click', showModal);
});

场景 B:

$(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.

谁能解释一下为什么?

标签: javascriptjquery

解决方案


事件处理程序回调的第一个参数是事件对象。所以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>


推荐阅读