jquery click on href link - have to click twice

2019-05-24 04:23发布

问题:

The function works, but the popup will open only after the button is clicked twice (and then, subsequent clicks get the action on the first click).

$(document).ready(function(){
    $('a#printPosBtn').on('click', function(e) {
        e.preventDefault();
        $('.printPopup').popupWindow({ 
            centerBrowser:1,
            height:500,
            width:720,
            scrollbars: 1,
            resizable: 1
        });
        return false;
    });
});

What's wrong?

回答1:

I think that is because you are actually initialising the plugin within the click handler. From a quick skim through the popupWindow docs it appears that the plugin takes care of binding a click handler for you, which means that your first click binds the popup functionality (including an onclick handler) so it only works upon click a second time. I would try:

$(document).ready(function() {

    $(".printPopup").popupWindow({
        centerBrowser: 1,
        height: 500,
        width: 720,
        scrollbars: 1,
        resizable: 1
    });

    // open popup by clicking on some other element
    $('#printPosBtn').on('click', function(e) {
        e.preventDefault();
        $(".printPopup").click();         
    });

});​