简体   繁体   中英

Issues calling external javascript file

I have a simple HTML file containing a list and a JS function that modifies the text of a list item when clicked on.

The code works when i have the HTML and the JS script inside the same .html file, but I would like to separate the JS code and put it in an external .js file and I can't seem to get the JS function to work when it's in the file.
I have provided the HTML and the JS code below.

Thank you in advance!!

My html code containing the referenced js script is as follows(js file is in the same directory):

<nav>
    <ul>
        <li id="homePage">Home
        </li>
        <li id="bookPage">Books
        </li>
        <li id="videoPage">Videos
        </li>
    </ul>

    <script src="navbar_listener.js"></script>
</nav>

The code found in navbar_listener.js is as follows:

function modifyText()
{
var t2 = document.getElementById("videoPage");
if (t2.innerHTML == "Videos")
{
t2.innerHTML = "VideoCHANGE";
}
else { t2.innerHTML = "Videos"; }

// add event listener to t2
var el = document.getElementById("videoPage");
el.addEventListener("click", modifyText,false);

Change

el.addEventListener("click", modifyText,false);

to

el.onclick= modifyText;

You have a syntax error. You missed a closing curly bracket at the end of your method. Try indenting your code better and also check the browser console for errors. It is a good way for debugging.

<nav>
  <ul>
    <li id="homePage">Home</li>
    <li id="bookPage">Books</li>
    <li id="videoPage">Videos</li>
  </ul>
</nav>

<script src="navbar_listener.js"></script>

And the JS file:

function modifyText(){
  var t2 = document.getElementById("videoPage");
  if (t2.innerHTML == "Videos"){
    t2.innerHTML = "VideoCHANGE";
  } else {
    t2.innerHTML = "Videos";
  }
} // YOU MISSED THIS ONE.

// add event listener to t2
var el = document.getElementById("videoPage");
el.addEventListener("click", modifyText,false);

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