简体   繁体   中英

“onclick” of a button in a popup works only once

I have an html/php webpage (the file is called searchresults.php) that imports jquery mobile. When you enter the page, the url is usually something like

www.domain.com/searchresults.php?&sort="off"&max="5"

In this example sorting is off and only 5 items are displayed. On that page is a button that opens a popup where I want the user to be able to change these settings. I use the built-in jquery mobile popup. On that popup you can toggle "sort" on/off and you can enter a new maximum. On the popup is an "ok" button to confirm your new settings. It looks like this:

<a href="" id="okbutton" data-role="button" onclick="sortAgain();">OK</a>

The sortAgain(); function in javascript looks like this:

function sortAgain();
{
    //some code to get the necessary variables//
    ...

    //change the href of the button so you reload the page
    document.getElementById("okbutton").href = "searchresults.php" + "?keyword=" + var1 + "&sort=" + var2 + "&max=" + var3
 }

So, basically, right before the "ok" button navigates to another page, I set its href of the page where it should navigate too.

This scheme works, and the searchresults.php file is fetched again from the server and re-interpreted (with the new variables in the url).

However, if i try to change the settings again after changing it once, the popup just does nothing! In other words, the href of the ok button on the popup stays empty and the javascript function sortAgain() is not called. I don't understand why it calls the onclick method perfectly fine the first time, but then refuses to call it again?

I assume it has something to do with the fact that the popup html code is an integral part of searchresult.php file, and that hrefing to the same page gives problems? The popup is pure html, no php is involved in the popup code. and again, it works fine the first time.

You should check out how to attach events via JavaScript. See here: javascript attaching events

You need to use the "pageinit" event when setting up click handlers in JQM: http://api.jquerymobile.com/category/events/

Here is an example of how to bind click handlers when the page is first loaded.

$( document ).on( "pageinit", "#that-page", function() {
    $('#okbutton').on( "click", "#that-page", function( e ) { 
        $(this).attr("href", "searchreslts.php");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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