简体   繁体   中英

href doesn't load html's script

I've created a navigation bar in my webpage that links to different html files using href. The navbar.html has javascript to change the active link UI to show the user which item is clicked that I load like this.

navbar.html

<script>
   require('../assets/navbar.js');
</script>

navbar.js

$('#sidebar-button').click(function() {
    $('.ui.sidebar').sidebar('toggle');
 });

 $('div.sidebar-items > a').click(function() {
    $(this).attr('class', 'active item');
    $(this).siblings().attr('class', 'item');

    $(this).find('i').addClass('teal');
    $(this).siblings().find('i').removeClass('teal');

    $('.ui.sidebar').sidebar('toggle');
 });

It will successfully load another html page and I include the same navbar.html in my search.html with:

search.html

<script> $(function() {
         $('#navbar').load("../html_pages/navbar.html", function() {
               $.getScript("../assets/navbar.js")
           });
      });
</script>

However, the active link does not change to the respective page that is clicked (in this case search.html). The navbar just loads as the original html was written. How can I make the navbar.js also execute and change the html when another page is loaded?

Unless it's also a Jquery function, require() is a Node JavaScript function. You should be getting an error something along the lines of "require is not a function," or "require is not defined."

I believe your HTML
<script> require('../assets/navbar.js'); </script>

Should be
<script src='../assets/navbar.js'></script>

This will load the JavaScript from the source src file into the HTML page that the script is put into, although that is a relative tag so it may need to be modified to be relative to whatever page you're applying it to.

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