简体   繁体   中英

PHP/Jquery:refresh the captcha on click with jquery

I use a captcha in my login form and I want to refresh the captcha when I click the captcha itself!but it doesn't work! my html code:

<cite class="fr">
    <img id="captcha_img" src="securimage/securimage_show.php" alt="点击图片刷新验证码"  />
</cite>

my jquery code:

$('#captcha_img').click(function(){
    //alert("hh");
    $('#captcha_img').attr("src","securimage/securimage_show.php"); 
});

I also search some docs about this question and try some other ways,but it still doesn't work,can someone give me some ideas?

Browser is probably caching image. Try this:

$('#captcha_img').click(function() {
    var imageUrl = 'securimage/securimage_show.php?' + new Date().getTime();
    $(this).attr('src', imageUrl); 
});

Both methods below should work ( uncomment one by one and try it ):

jQuery(function ($) {

    $('#captcha_img').on( 'click', function() {
        // $(this).attr( "src","securimage/securimage_show.php?"+Math.random() ); 
        // $(this).attr( "src","securimage/securimage_show.php?"+new Date().getTime() );
    });

});
$('#captcha_img').click(function(){
    //alert("hh");
    $('#captcha_img').attr("src","securimage/securimage_show.php"); 
     return false;
});

Or use e.preventDefault() like

$('#captcha_img').click(function(e){
    e.preventDefault();
    $('#captcha_img').attr("src","securimage/securimage_show.php"); 
     //return false;
});

tell me if that works. In this case, return false will work just fine because the event doesn't need to be propagated.

DEMO

$(function () {
    $('#foo').click(swapImages);
    var secondImg = 'http://digital-photography-school.com/wp-content/uploads/2013/03/Acorn256.png';
    function swapImages() {
        var img = $("<img id='foo' src='" + secondImg + "' />");
        $(this).replaceWith(img);
        $(img).click(swapImages);
    }
});

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