如何在href中匹配'/#'

时间:2015-03-13 12:59:49

标签: javascript jquery regex

我使用此代码来匹配href属性是否以#开头并根据其添加类:

$('.navbar-nav a').each(function(index, element) {
    if($(element).attr("href").match("^#"))
    {
        //Add class to inernal links
        $(element).addClass("internal");
    }
    else
    {
        //Add class to external links
        $(element).addClass("external");
    }
});

如果href以/#开头,我现在遇到问题。我试过' ^ /#'但它没有用。

我会感激任何帮助。

更新

以下是我使用的完整代码:

jQuery.noConflict();
(function( $ ) {
  $(function() {
/*********************************************************************************************************/
/* -------------------------------------- Navigation ------------------------------------------ */
/*********************************************************************************************************/
//Add class to inernal and external links
$('.navbar-nav a').each(function(index, element) {
    if($(element).attr("href").match(/^\/?#/))
    {
        //Add class to inernal links
        $(element).addClass("internal");
    }
    else
    {
        //Add class to external links
        $(element).addClass("external");
    }
});

var lastId,
    topMenu = $(".navbar-nav"),
    topMenuHeight = topMenu.outerHeight(),
    // All list items without external links
    menuItems = topMenu.find("a").not(".external"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function() {
        var item = $($(this).attr("href"));
        if (item.length) {
            return item;
        }
    });

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
    if (!$(this).hasClass("dropdown-toggle")) {
        var href = $(this).attr("href"),
            offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
        $('html, body').stop().animate({
            scrollTop: offsetTop
        }, 1450,  'easeInOutQuart');
        e.preventDefault();
    }
});

// Bind to scroll
$(window).scroll(function() {
    // Get container scroll position
    var fromTop = $(this).scrollTop() + topMenuHeight;

    // Get id of current scroll item
    var cur = scrollItems.map(function() {
        if ($(this).offset().top < fromTop)
            return this;
    });
    // Get the id of the current element
    cur = cur[cur.length - 1];
    var id = cur && cur.length ? cur[0].id : "";

    if (lastId !== id) {
        lastId = id;
        // Set/remove active class
        menuItems
            .parent().removeClass("active")
            .end().filter("[href=#" + id + "]").parent().addClass("active");
    }
});


/*********************************************************************************************************/
/* -------------------------------------- Home part - 100% hight ------------------------------------------ */
/*********************************************************************************************************/
jQuery.fn.refresh = function() {
    var s = skrollr.get();

    if (s) {
        s.refresh(this);
    }
    return this;
};

function fullHeight() {
    windowHeight = $(window).height();
    $('#home, .tp-banner-container').css('height', windowHeight).refresh();
};
fullHeight();
$(window).resize(function() {
    fullHeight();
});


/*********************************************************************************************************/
/* -------------------------------------- H2 big shadow ------------------------------------------ */
/*********************************************************************************************************/
$("h2").each(function () {
    var h2 = $(this);
    var span = h2.parent().find("span.title-shadow");
    span.append(h2.html());
});


/*********************************************************************************************************/
/* -------------------------------------- Back to top ------------------------------------------ */
/*********************************************************************************************************/
$(".logo").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "easeInOutQuart");
  return false;
});


/*********************************************************************************************************/
/* -------------------------------------- Contact form ------------------------------------------ */
/*********************************************************************************************************/
(function(e) {
    function n(e, n) {
        this.$form = e;
        this.indexes = {};
        this.options = t;
        for (var r in n) {
            if (this.$form.find("#" + r).length && typeof n[r] == "function") {
                this.indexes[r] = n[r]
            } else {
                this.options[r] = n[r]
            }
        }
        this.init()
    }
    var t = {
        _error_class: "error",
        _onValidateFail: function() {}
    };
    n.prototype = {
        init: function() {
            var e = this;
            e.$form.on("submit", function(t) {
                e.process();
                if (e.hasErrors()) {
                    e.options._onValidateFail();
                    t.stopImmediatePropagation();
                    return false
                }
                return true
            })
        },
        notEmpty: function(e) {
            return e != "" ? true : false
        },
        isEmail: function(e) {
            return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e)
        },
        isUrl: function(e) {
            var t = new RegExp("(^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|(www\\.)?))[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?", "gim");

            return t.test(e)
        },
        elClass: "",
        setClass: function(e) {
            this.elClass = e
        },
        process: function() {
            this._errors = {};
            for (var t in this.indexes) {
                this.$el = this.$form.find("#" + t);
                if (this.$el.length) {
                    var n = e.proxy(this.indexes[t], this, e.trim(this.$el.val()))();
                    if (this.elClass) {
                        this.elClass.toggleClass(this.options._error_class, !n);
                        this.elClass = ""
                    } else {
                        this.$el.toggleClass(this.options._error_class, !n)
                    }
                    if (!n) {
                        this._errors[t] = n
                    }
                }
                this.$el = null
            }
        },
        _errors: {},
        hasErrors: function() {
            return !e.isEmptyObject(this._errors)
        }
    };
    e.fn.isValid = function(t) {
        return this.each(function() {
            var r = e(this);
            if (!e.data(r, "is_valid")) {
                e.data(r, "is_valid", new n(r, t))
            }
        })
    }
})(jQuery)


/*********************************************************************************************************/
/* -------------------------------------- Ajax contact form ------------------------------------------ */
/*********************************************************************************************************/
$('#forms').isValid({
    'name': function(data) {
        this.setClass(this.$el.parent());
        return this.notEmpty(data);
    },
    'email': function(data) {
        this.setClass(this.$el.parent());
        return this.isEmail(data);
    },
    'subject': function(data) {
        this.setClass(this.$el.parent());
        return this.notEmpty(data);
    },
    'message': function(data) {
        this.setClass(this.$el.parent());
        return this.notEmpty(data);
    }
}).submit(function(e) {
    e.preventDefault();

    var $this = $(this);
    $.ajax({
        'url': $(this).attr('action'),
        'type': 'POST',
        'dataType': 'html',
        'data': $(this).serialize()
    }).done(function(response) {
        $this.find('.notification').show();
        $this.find('input[type="text"], input[type="email"], textarea').val('');
    });
    return false;
});

$('.notification').on('click', function() {
    var $this = $(this);
    $this.hide();
});


/*********************************************************************************************************/
/* -------------------------------------- Sticky navigation ------------------------------------------ */
/*********************************************************************************************************/
$("#navigation").sticky({
    topSpacing: 0,
    className: 'sticky',
    wrapperClassName: 'main-menu-wrapper'
});


/*********************************************************************************************************/
/* -------------------------------------- Wow Scroll Animate ------------------------------------------ */
/*********************************************************************************************************/
wow = new WOW({
    boxClass: 'wow',
    animateClass: 'animated',
    offset: 100,
    movile: true

});


/*********************************************************************************************************/
/* -------------------------------------- Skrollr and Wow init ------------------------------------------ */
/*********************************************************************************************************/
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {

    //Skrollr
    var s = skrollr.init({
        edgeStrategy: 'set',
        forceHeight: true,
        smoothScrolling: true,
        easing: {
            wtf: Math.random,
            inverted: function(p) {
                return 1 - p;
            }
        }
    });
    //Wow init
    wow.init();
}


/*********************************************************************************************************/
/* -------------------------------------- Charts, Skils ------------------------------------------ */
/*********************************************************************************************************/
$('.chart').waypoint(function() {
    $(this).easyPieChart({
        animate: 1000,
        size: 200,
        lineWidth: 5,
        trackColor: "#fff",
        barColor:"#de3926",
        scaleColor: false,
        size: 200,
        onStep: function(from, to, percent) {
            jQuery(this.el).find('.percent').text(Math.round(percent));
        }
    });
}, {
    triggerOnce: true,
    offset: 'bottom-in-view'
});


$(document).ready(function() {
        /*********************************************************************************************************/
    /* -------------------------------------- Ajax our team ------------------------------------------ */
    /*********************************************************************************************************/
    $('.ajax-popup-team').magnificPopup({
        type: 'ajax',
        showCloseBtn: true,
        modal: true,
        closeOnContentClick: false,
        overflowY: 'scroll'
    });


    /*********************************************************************************************************/
    /* -------------------------------------- Ajax portfolio page ------------------------------------------ */
    /*********************************************************************************************************/
    $('.ajax-popup-portfolio').magnificPopup({
        type: 'ajax',
        showCloseBtn: true,
        modal: true,
        closeOnContentClick: false,
        overflowY: 'scroll',
        gallery: {
           enabled: true,
           arrowMarkup: '<button title="%title%" type="button" class="portfolio mfp-arrow mfp-arrow-%dir%"></button>'
        }
    });


    /*********************************************************************************************************/
    /* -------------------------------------- Portfolio gallery ------------------------------------------ */
    /*********************************************************************************************************/
    $('.gallery-item-content').each(function() { // the containers for all your galleries
        $(this).magnificPopup({
            delegate: '.gallery-item', // the selector for gallery item
            type: 'image',
            gallery: {
                enabled: true
            }
        });
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Video ------------------------------------------ */
    /*********************************************************************************************************/
    $('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
        disableOn: 700,
        type: 'iframe',
        mainClass: 'mfp-fade',
        removalDelay: 160,
        preloader: true,
        fixedContentPos: true
    });


    /*********************************************************************************************************/
    /* -------------------------------------- Owl carousel ------------------------------------------ */
    /*********************************************************************************************************/
    $("#carousel-our-testimonials").owlCarousel({
        autoPlay: 3000,
        stopOnHover: true,
        navigation: false,
        paginationSpeed: 1000,
        goToFirstSpeed: 2000,
        singleItem: true,
        autoHeight: true,
        transitionStyle: "fade"
    });
    $("#carousel-our-clients").owlCarousel({
        autoPlay: 10000,
        stopOnHover: true,
        navigation: true,
        paginationSpeed: 1000,
        goToFirstSpeed: 3500,
        singleItem: false,
        autoHeight: true,
        transitionStyle: "fade",
        navigationText: [
        "<i class='fa fa-angle-left'></i>",
        "<i class='fa fa-angle-right'></i>"
        ]
    }); 
    $("#blog-single").owlCarousel({
        navigation: true, // Show next and prev buttons
        pagination: false,
        slideSpeed: 300,
        paginationSpeed: 400,
        navigationText: [
            "<i class='fa fa-chevron-left'></i>",
            "<i class='fa fa-chevron-right'></i>"
        ],
        singleItem: true
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Dropdown Menu Fade  ------------------------------------------ */
    /*********************************************************************************************************/
    $(".dropdown").hover(
        function() {            
            $('.dropdown-menu', this).fadeIn(275);
            $(this).addClass("open");
        },
        function() {            
            $('.dropdown-menu', this).fadeOut(275);
            $(this).removeClass("open");
    });


    /*********************************************************************************************************/
    /* -------------------------------------- Placeholder fix for IE  ------------------------------------------ */
    /*********************************************************************************************************/
    (function($) {       
        if (!Modernizr.csstransforms3d) {
            $('[placeholder]').focus(function() {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                    input.removeClass('placeholder');
                }
            }).blur(function() {
                var input = $(this);
                if (input.val() == '' || input.val() == input.attr('placeholder')) {
                    input.addClass('placeholder');
                    input.val(input.attr('placeholder'));
                }
            }).blur().parents('form').submit(function() {
                $(this).find('[placeholder]').each(function() {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                })
            });
        }
    })

});


/*********************************************************************************************************/
/* -------------------------------------- Count  ------------------------------------------ */
/*********************************************************************************************************/
$('#statistic').waypoint(function() {
    $('.timer').countTo();
}, {
    triggerOnce: true,
    offset: 'bottom-in-view'
});


/*********************************************************************************************************/
/* -------------------------------------- Show and hide color-switcher  ------------------------------------------ */
/*********************************************************************************************************/
$(".color-switcher .switcher-button").click(function(){
    $( ".color-switcher" ).toggleClass("show-color-switcher", "hide-color-switcher", 800);
}); 


/*********************************************************************************************************/
/* -------------------------------------- Color Skins  ------------------------------------------ */
/*********************************************************************************************************/
$('a.color').click(function(){
    var title = $(this).attr('title');
    $('#style-colors').attr('href', 'css/color-schemes/' + title + '.css');
    return false;
});


/*********************************************************************************************************/
/* -------------------------------------- Loader  ------------------------------------------ */
/*********************************************************************************************************/
$(window).load(function() {
    $("#loader").delay(450).fadeOut(800);
    $(".preload-gif").addClass('fadeOut');

});

});
})(jQuery);

2 个答案:

答案 0 :(得分:3)

如果要匹配两者,可以将正则表达式更改为:

/^\/?#/

问号是一个0或1个量词,它将匹配开头是否有/

请在此处查看:http://www.regexr.com/3ajoo

我也使用你的代码并试图找到你所遇到的错误:我认为这个问题的答案没有错误。你的错误必须是别的。 尝试将函数包装在$(document).ready()中,以确保在搜索元素之前加载DOM。

&#13;
&#13;
$(document).ready(function() {

  $('.navbar-nav a').each(function(index, element) {
    if ($(element).attr("href").match(/^\/?#/)) {
      //Add class to inernal links
      $(element).addClass("internal");
    } else {
      //Add class to external links
      $(element).addClass("external");
    }
  });

});
&#13;
.external {
   color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="navbar-nav">
    <a href="/#something">Link</a>
  </li>
  <li class="navbar-nav">
    <a href="/#somethingelse">Link</a>
  </li>
  <li class="navbar-nav">
    <a href="#someanchor">Link</a>
  </li>
  <li class="navbar-nav">
    <a href="#someotheranchorthing">Link</a>
  </li>
  <li class="navbar-nav">
    <a href="http://www.example.com">Link</a>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用/作为分隔符。

if($(element).attr("href").match(/^\/#/))
相关问题