简体   繁体   中英

JQuery on('click') works only once

I know there's a lot of questions like this, but still can't figure it out.

<div class="message"></div>
<button id="getMessage">Get Quote</button>
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(data) {
    var content = data[0].content + data[0].title;
    $("#getMessage").on("click", function() {
        $(".message").html(content);
    });
});

the problems is that on("click") only works once, but I want it to work every time the button is clicked. What am I doing wrong?

You seem to be assuming that just because "quotesondesign" gives you a random quote, that var content is somehow magical in its ability to generate further random quotes. This is not the case.

All your on('click') does is take the single random quote that was fetched and display it. If it's already been displayed, it will just display it again, replacing the first and seeming to do nothing.

You need to put that $.getJSON call inside the on('click') so that the "quotesondesign" call is made a second time to retrieve another quote.

Alternatively, increase posts_per_page to a higher number to get a selection of quotes, and move the var content inside the on('click') , replacing 0 with some suitable random number (eg. var selected = Math.floor(Math.random()*data.length), content = data[selected].content + data[selected].title; )

Try this:

$("#getMessage").on("click", function() {
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(data) {
        var content = data[0].content + data[0].title;
        $(".message").html(content);
    });
});

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