Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

How to call external JavaScript function in HTML

I have a small chunk of code I can't seem to get working. I am building a website and using JavaScript for the first time. I have my JavaScript code in an external file 'Marq_Msg.js' which looks like this:

var Messages = new Array();
Messages[0] = "This is message 1";
Messages[1] = "This is message 2";
Messages[2] = "This is message 3";
Messages[3] = "This is message 4";  

function scroll_messages()
{
  for (var i = 0; i < Messages.length; i++)
        document.write(Message[i]); 
}

and in my HTML file 'Index.html' I am trying to call it like this:

    <div id="logo">
        <marquee scrollamount="5" direction="left" loop="true" height="100%" width="100%">
        <strong><font color="white"><script src="Marq_Msg.js">scroll_messages()</script></font></strong>
        </marquee>
    </div>

The 'logo' div is a CSS piece that I'm trying to marquee inside of. If I put the code embedded inside the 'head' tag and call it, it works perfectly! There are a few other things id like to do with this code (like space the messages out a little) but I can't get the code to work in the first place. I've also tried adding:

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

in the 'head' tag with a separate call, that was a no go. I also tried instead using:

<script type="text/javascript" src="Marq_Msg.js">scroll_messages()</script>

Hell, i even had the function try returning a string (even hardcoded a simple "hello" to be returned) but that didnt work either with and without the 'type':

//Marq_Msg.js
function scroll_messages()
{
   return "hello";
}

//index.html
<script type="text/javascript" src="Marq_Msg.js">document.write(scroll_messages())</script>

What am I missing? Any help would be greatly appreciated!! I've looked all over Google, and every site I find wants to do it using some 'form'. I just want messages to be displayed across, no form attached.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...