Switch id with jquery as condition

perhaps too simple what I ask, or maybe not. Anyway, I need to call a specific anchor of the page when I click on the link, it enters a specific URL with a specific anchor list down to that anchor.

I am doing this with jquery as follows:

$(document).ready(function() {

    var anchor = window.location.hash.substring(1);

    if(anchor!="") {

        var newAnchor= "'#anchor-" +anchor+"'";

        $(newAnchor).trigger("click");

    }

});     

I think this is impossible, of course, I never saw him, I get the following error:

Uncaught Error: Syntax error, unrecognized expression: '#anchor-2015'

Is it possible to dynamically call a selector? Was there another way?

Thanks.

+4
source share
2 answers

Yes it is possible. You have invalid quotation marks.

$(document).ready(function() {

    var anchor = window.location.hash.substring(1);


if(anchor!=""){

    var newAnchor= "#anchor-" + anchor;

    $(newAnchor).trigger("click");


    }


}); 
+1
source

Delete single quotes; they are not needed.

var newAnchor= "#ancla-" + anchor;
+3
source

Source: https://habr.com/ru/post/1627883/


All Articles