I have an animated navigation via some jQuery functions. It all works fine but one thing is making me crazy. The last item (item nb. 5) should redirect you to new page but it does not happen. I have the condition on first few first lines of code below

$(document).ready(function(){
    $('li > a').on('click', function(e) {
        if ($(this).parent().has('p')) {        
            e.preventDefault();
        }

        if (!$(this).hasClass('active')) {
            $('li a').next('p').stop().slideUp();
            $(this).next('p').stop().slideDown();
            $('li a').removeClass('active');
            $(this).addClass('active');
        }
        else if ($(this).hasClass('active')) {
            $(this).next('p').stop().slideUp();
            $(this).removeClass('active');
        }

    })

}) 

DEMO: http://jsfiddle.net/SQTcN/2/

有帮助吗?

解决方案

has(selector)

Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

Returns: jQuery

.has() returns a jQuery object.

Use .find('p').length or .has('p').length instead of .has('p'):

$(document).ready(function(){
    $('li > a').on('click', function(e) {
        
        if ($(this).parent().find('p').length) {
            e.preventDefault();
        }

        if (!$(this).hasClass('active')) {
            $('li a').next('p').stop().slideUp();
            $(this).next('p').stop().slideDown();
            $('li a').removeClass('active');
            $(this).addClass('active');
        }
        else if ($(this).hasClass('active')) {
            $(this).next('p').stop().slideUp();
            $(this).removeClass('active');
        }
    });
}); 

JSFIDDLE

其他提示

.has() returns a jQuery object not a boolean

Just change your if to this:

if (!($(this).hasClass("odkaz"))) { 
    e.preventDefault();
}

CODE:

$(document).ready(function(){
    $('li > a').on('click', function(e) {
        if (!($(this).hasClass("odkaz"))) { 
            e.preventDefault();
        }

        if (!$(this).hasClass('active')) {
            $('li a').next('p').stop().slideUp();
            $(this).next('p').stop().slideDown();
            $('li a').removeClass('active');
            $(this).addClass('active');
        }
        else if ($(this).hasClass('active')) {
            $(this).next('p').stop().slideUp();
            $(this).removeClass('active');
        }

    })

}) 

DEMO

.has() doesn't return a boolean. It returns a jQuery object. From the docs:

Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

So, you'd need to do something like:

if($(this).parent().has('p').length)

Or better yet, you don't need to traverse up to the parent to traverse back down. Just simply do:

if($(this).siblings('p').length)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top