Zeroclipboard not copying on first Click

2019-09-02 19:00发布

I have the code and it is not working on first click, but on the second click it is working.

$("#btnCopiar").on("click",function(){
        var clipBoardObj = new ZeroClipboard($("#btnCopiar"), {
              moviePath: "../thirdparty/ZeroClipboard.swf"
        });;
        // Create your data here to copy to the clipboard and assign to a variable name data 
         var data =   "DATA IS COMING FROM SERVER OT TEXT INPUT";
                clipBoardObj.on("copy", function (event) {                  
                var clipboard = event.clipboardData;
                  clipboard.setData( "text/plain", data );
        });

    });

<button id="btnCopiar">Copiar</button>

Even if I have initialized the clipboard outside the click event, it is not working

1条回答
疯言疯语
2楼-- · 2019-09-02 19:57

I wonder if this has to with the synchronous way you have written the code.

Your line var data = ... implies that the variable data is receiving its information from a call to the server that only happens right at that moment. (I'm making some assumptions about code you have deleted in order to make the question more concise and understandable, though I could be wrong about that.) That data is going to take a little while to arrive. However, immediately after that line you are using the data variable in the clipBoardObj.on("copy", function(event) {... function. The first time you run that function, the data will not yet have arrived. However, some time will elapse before the user clicks the button a second time. When that happens, there may have been enough time for the first call to the server to have returned, and data will have some data. Note, however, that the second time you run that function, it will only be using the data from the first call to the server, which may or may not be acceptable.

查看更多
登录 后发表回答