Pass dynamic id value jquery div jump to function

前端 未结 4 1152
忘了有多久
忘了有多久 2021-01-16 14:31

I am stuck at jquery div jump to problem. The problem is that i am creating dynamic and dynamic div also say <

相关标签:
4条回答
  • 2021-01-16 14:32

    String Concatenation:

    $("#" + this.id + "_div").offset().top
    

    Note that there is no need to create unique IDs, DOM duo to having tree-like structure provides many different methods for traversing and selecting the target elements.

    Since you are generating the elements dynamically you should also delegate the events, you can add classes to your elements and use the on method:

    $('#aStaticParentElement').on('click', '.anchors', function() {
       // TODO:
       // select the target element either by traversing 
       // or by using an identifier
    });
    
    0 讨论(0)
  • 2021-01-16 14:48

    User this line

    $("#" + $(this).attr("id") + "_div").offset().top
    

    ...

    0 讨论(0)
  • 2021-01-16 14:51
    $(document).ready(function (){
            $(".click").click(function (){
                alert ("test");
                var divID = '#' + $(this).attr('id') + '_div';
                    $('html, body').animate({
                        scrollTop: $(divID).offset().top
                    }, 1000);
            });
        });
    

    And add <a class="click" ...

    0 讨论(0)
  • 2021-01-16 14:55

    Visualize it here

    First, since you have multiple links, use a class to group them:

    HTML

    <a href="#" id="1_1" class="click">Click me 1_1</a>
    <a href="#" id="1_2" class="click">Click me 1_2</a>    
    <a href="#" id="1_3" class="click">Click me 1_3</a>
    

    jQuery

    $(document).on('click', '.click', function (e) {
        var theID = $(this).attr('id');
        $('html, body').animate({
            scrollTop: $('#' + theID + '_div').offset().top
        }, 1000);
        return false;
    });
    

    I did this with the slight assumption you were dynamically creating these links (hence the delegation). If they are static and won't change during page load, you can use $('.click').click(function()... instead of $(document).on('click', '.click', function()...

    0 讨论(0)
提交回复
热议问题