[对象对象] 是什么意思?

2022-01-30 00:00:00 object jquery javascript

我试图提醒一个函数的返回值,我在提醒中得到了这个:

I am trying to alert a returned value from a function and I get this in the alert:

[object Object]  

这是 JavaScript 代码:

Here is the JavaScript code:

<script type="text/javascript">
$(function ()
{
    var $main = $('#main'),
    $1 = $('#1'),
    $2 = $('#2');

    $2.hide(); // hide div#2 when the page is loaded

    $main.click(function ()
    {
        $1.toggle();
        $2.toggle();
    });

    $('#senddvd').click(function ()
    {
       alert('hello');
       var a=whichIsVisible();
       alert(whichIsVisible());
    });

    function whichIsVisible()
    {
        if (!$1.is(':hidden')) return $1;
        if (!$2.is(':hidden')) return $2;
    }

});

</script>

whichIsVisible 是我要检查的函数.

推荐答案

对象到字符串的默认转换是"[object Object]".

The default conversion from an object to string is "[object Object]".

当您处理 jQuery 对象时,您可能想要这样做

As you are dealing with jQuery objects, you might want to do

alert(whichIsVisible()[0].id);

打印元素的 ID.

正如评论中提到的,您应该使用 Firefox 或 Chrome 等浏览器中包含的工具通过执行 console.log(whichIsVisible()) 而不是 alert.

As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.

旁注:ID 不应以数字开头.

Sidenote: IDs should not start with digits.

相关文章