JS:从按钮调用函数

JS: Calling a function from a button

本文关键字:调用 函数 按钮 JS      更新时间:2023-09-26

我正在学习纯JavaScript。我的问题很基本,我希望有人能好心地给我指出正确的方向。在画布绘图练习中,我使用以下函数:

drawingTools.pencil = function () {
    document.getElementById("activeTool").value = "Pencil";
    this.mousedown = function (evt) {
        isDrawing = true;
        startX = getendY(tmp_canvas, evt);
    };
    this.mousemove = function (evt) {
        compositeDraw()
        endY = getendY(tmp_canvas, evt);
        if (isDrawing) {
            tmp_context.beginPath();
            tmp_context.moveTo(startX.x, startX.y);
            tmp_context.lineTo(endY.x, endY.y);
            tmp_context.lineJoin = 'round';
            tmp_context.lineCap = "round";
            tmp_context.stroke();
            tmp_context.strokeStyle = defaultLineColor;
            tmp_context.lineWidth = defaultLineThickness;
        }
        startX = endY;
    };
    this.mouseup = function (evt) {
        isDrawing = false;
        drawtmp_contextOncanvas();
    }
};

使用下面的代码行可以很好地工作:

pencil.addEventListener('click', this.changeDrawingTool, false);

当我尝试使用按钮图标调用drawingTools.pencil函数时,如下:

 document.getElementById("iconPencil").addEventListener('click', drawingTools.pencil, false);

上述功能未被触发。

演示:

http://jsfiddle.net/pgyu7/

在第二个选项

 document.getElementById("iconPencil").addEventListener('click', drawingTools.pencil, false);

this指向#iconPencil元素。此元素不实现mousedown, mousemove

要避免丢失this,可以使用bind

document.getElementById("iconPencil").addEventListener('click', drawingTools.pencil.bind(pencil), false);