문제

I have a Wordpress site which has a gallery on a page visible to all users.

The idea is that if a non-member clicks a gallery thumbnail, they get redirected to a signup page. If a user is logged in, the image displays in a lightbox as usual.

I'm playing with this jQuery code and can't get the preventDefault bit working - I think it's because it's inside a conditional.

$('.ngg-gallery-thumbnail a').on('click', function(event){

        if (!$('body').hasClass('logged-in')) {
            alert('Not logged in!');
            event.preventDefault();
        }
    });

Also I'm pretty sure there'll be a more secure way of doing this using PHP - if anyone can point me in the right direction I'd be most grateful!

도움이 되었습니까?

해결책

Try like

$('.ngg-gallery-thumbnail a').on('click', function(event){
    event.preventDefault();
    if (!$('body').hasClass('logged-in')) {
        alert('Not logged in!');
        return false;
    }
    $(this).addClass('lightbox');
});

Dont give the lightbox class before,first check for the condition and then if it satisfies then add class for the lightbox

다른 팁

The correct format of on() method is this:

$('.ngg-gallery-thumbnail').on('click', 'a', function(){
    if (!$('body').hasClass('logged-in')) {
        alert('Not logged in!');
        return false;
    }
    return true;
});

Also, there's no need of preventDefault() method here, since you are using return false here.

Returning false performs three tasks when called:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top