質問

Can someone please explain what this code does.. Like the 'split' function etc.

$("button").click(function() {
    var id=this.id.split('[');
    var d_id=id[1].split(']')
    var ii=d_id[0]
    $('html, body').animate({
        scrollTop: $('[id='+ii+']').offset().top
    }, 2000);
});
役に立ちましたか?

解決

  1. It attaches a click eventhandler to every <button> tag.
  2. In the handler it extracts the "foo" from the button's id attribute if it is for example "bar[foo]".
  3. It animates a page scroll to the postition of the element with the "foo" id (the "[id=...]" jQuery selector).

The string.split is a string function which splits the string into an array based on the given separator, here "[" and then "]", check the documentation.

Briefly, the offset() jQuery function returns the top and left pixel coordinates of the first element matched by the given selector, check the documentation.

So as a result, when you click a <button> with id "bar[foo]", the page will do an animated vertical scroll so that the element with id "foo" will be at the top or the window.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top