TypeError:无效' in'一个班级的操作数

时间:2016-01-27 13:44:58

标签: javascript jquery


我这里有一些JavaScript代码,它们使用JQuery创建一个类,然后使用类函数。

function sample(a, b)
{
    var id = a;
    var img_src = b;

    this.getId = function()
    {
        return id;
    };

    this.move = function(pTop, pLeft)
    {
        var p = $(this).position();
        var mov_top = p.top + pTop;
        var mov_left = p.left + pLeft;
        $(this).animate({
            top: mov_top,
            left: mov_left
        });
    }
}

我在点击按钮时调用它:

<button onclick="create(3);">Click me :D</button>

<script>            
    function create(id)
    {
        var mySample = new sample(id, 'url');
        mySample.move(50, 50);
    }   
</script>

这会返回错误TypeError:invalid&#39; in&#39;操作数a但我不知道它来自哪里......

有人有想法吗?

1 个答案:

答案 0 :(得分:0)

尝试将create()传递给3,而不是a sample() button,设置css position { {1}}到relative

&#13;
&#13;
function sample(a, b)
{
    var id = a;
    var img_src = b;

    this.getId = function()
    {
        return id;
    };

    this.move = function(pTop, pLeft)
    {
        var p = $(a).position();
        var mov_top = p.top + pTop;
        var mov_left = p.left + pLeft;
        $(a).animate({
            top: mov_top,
            left: mov_left
        });
    }
}
&#13;
button {
  position:relative;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button onclick="create(this);">Click me :D</button>

<script>            
    function create(id)
    {
        var mySample = new sample(id, 'url');
        mySample.move(50, 50);
    }   
</script>
&#13;
&#13;
&#13;