简体   繁体   中英

When linking to a page anchor, how do I invoke JS code there?

My website has a FAQ page that, by default, shows only the questions, not the answers, to prevent clutter (there may be better ways, feel free to make suggestions).

To see an answer, the user has to click on the question, which then will fold open the answer. This is done browser-side, with Javascript and jQuery, like this:

<script type="text/javascript" >
    $(document).ready(function(){
        $(".trigger").click(function(){
            $(this).toggleClass("active").next().slideToggle("fast");
        });
    });
</script>

The questions are declared with the "trigger" CSS class.

Now, I link to the FAQ questions from other pages, using anchors. This will scroll the page to the question but does not reveal the answer automatically.

I like to reveal the answer when the user clicks on an anchored link to a FAQ question.

How can I accomplish this? Preferably without server-side (php) code, but if that's necessary, I can do that as well.

Here's an example link to my page:

http://apps.tempel.org/FindAnyFile/support.php#catsearch

You can check in javascript after the page is loaded whether the url has an anchor target, and if so, look up your anchor by that, simulating a click. If you know what you want to do there may be a more direct approach to twirling it open rather than sending doing the click.

I see you have jQuery included and already have a .ready so I would add this to it:

$(document).ready(function() {
    if(window.location.hash != '') {
        $(window.location.hash).click();
    }
})

When you want to show the answer, you can add a query string parameter, which your support.php checks on pageload. If there is such a parameter, find the ID in the URL and call whatever function can show the answer.

For example, link to

http://apps.tempel.org/FindAnyFile/support.php?showanswer=true#catsearch

and then, on pageload:

const urlParams = new URLSearchParams(window.location.search);
const showAnswer = urlParams.has('showanswer');
if (showAnswer) {
  $('#' + window.hash).toggleClass("active").next().slideToggle("fast");
}

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