简体   繁体   English

将内联Javascript中的变量传递到单独文件中的单击处理程序

[英]Passing variable from inline Javascript to click handler in separate file

I have some inline javascript for using Signature Pad https://github.com/szimek/signature_pad It looks like this: 我有一些用于使用Signature Pad https://github.com/szimek/signature_pad的嵌入式JavaScript,它看起来像这样:

var signaturePad = new SignaturePad(canvas, {
  backgroundColor: 'rgb(255, 255, 255)'
});
clearButton.addEventListener("click", function (event) {
  signaturePad.clear();
});

And in the footer i have a separate file included click.js 在页脚中,我有一个单独的文件,其中包含click.js

$('.send-signature').on( 'click', function( event ) {
        event.preventDefault();
        console.log(event);
        var $button = $(this);
        $button.prop("disabled",true);
        if (signaturePad.isEmpty()) {
            alert("Please provide a signature first.");
            return false;
        } 

} );

When I am clicking the button i get: Uncaught ReferenceError: signaturePad is not defined 当我单击按钮时,我得到: 未捕获的ReferenceError:未定义signaturePad

If I click the clearbutton button, it works fine. 如果我单击clearbutton按钮,它可以正常工作。 I can't understand what the problem is and how i should pass the signaturePad to the click handler. 我不明白问题是什么以及如何将signaturePad传递给单击处理程序。

Click.js is included below the inline javascript. 内嵌javascript下方包含Click.js

I have tried a lot of different solutions but i think this is the furthest i have come. 我尝试了许多不同的解决方案,但是我认为这是我所遇到的最远的解决方案。 Can somebody point me in the right direction and say why this is not working? 有人可以指出正确的方向,然后说为什么这行不通吗?

You could save the signaturePad variable in the window object 您可以将signaturePad变量保存在window对象中

window.signaturePad = new...

and then access it the same way 然后以相同的方式访问它

window.signaturePad.isEmpty()

this is not the most beautiful way of doing javascript, but I think it's OK for your purpose. 这不是执行javascript的最漂亮方法,但是我认为您可以这样做。

Can you try adding this right under your clearButton line? 您可以尝试在clearButton行下添加此权限吗? Also, maybe change send-signature to an addListener format and see if that changes anything. 另外,也许将send-signature更改为addListener格式,看看是否有任何改变。

$('.send-signature').on( 'click', function( event ) {
    event.preventDefault();
    console.log(event);
    var $button = $(this);
    $button.prop("disabled",true);
    if (signaturePad.isEmpty()) {
        alert("Please provide a signature first.");
        return false;
    } 

} );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM