简体   繁体   中英

using jquery 'this' to condense code

I try not to ask questions, but I can't figure out what should be very easy. I'm building a site for practice briannabaldwinphotography.com. I'm just trying to condense this so that I could just click on an anchor and it smooth scrolls to a <section> with an id the same name as the anchor. Ex: the 'about' li anchor has an href of #section_three and will scroll to the <section> with an id of section_three . I tried like 10 different variations and it won't work for me. Sort of what I'm looking for would be $(this).attr("href").offest().top} ....etc. Here is the code I want to condense. Thanks.

$(function() {
    $("[href='#section_three']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_three").offset().top}, 1000);
        return false;

    });
    $("[href='#section_two']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_two").offset().top}, 1000);
        return false;


    });
    $("[href='#section_four']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_four").offset().top}, 1000);
        return false;


    });
    $("[href='#section_one']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_one").offset().top}, 1000);
        return false;


    });

});

If you use the attribute starts with selector ( ^= ) you can get all elements with an href beginning with "#section_" , bind a handler to those, then within the handler use this.href to get the href of the particular element that was clicked:

$(function() {
    $("[href^='#section_']").on("click", function() {
        $("html body").animate({"scrollTop" : $(this.href).offset().top}, 1000);
        return false;
    });
});

Note that this.href does the same job as $(this).attr("href") , but more efficiently: no need to create a jQuery object to access a property of the element that you can get to directly.

Since the href in each case matches the target element it makes it fairly simple

$("[href^='#section']").on("click", function() {
        var targetSelector = $(this).attr('href');
        $("html body").animate({"scrollTop":$(targetSelector).offset().top}, 1000);
        return false;   
});

If those elements have a common class or better path through parent class and tags you could improve the initial selector performance

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