1

I have successfully called the following JavaScript code to populate an image and description using parameters. The image and description are in tags and are called imagePlaceHolder and descriptionPlaceHolder. As I say, this works perfectly.

function changeImage(imgName,descriptiveText)
{
    image = document.getElementById('imagePlaceHolder');
    image.src = imgName;

    text = document.getElementById('descriptionPlaceHolder');
    PlaceHolder.innerHTML=descriptiveText;
}

What I now require is to place the javascript in its own file and call it from the HTML page using <script src="xxxx.js"></script>

The problem is that the object in the <div> is not recognized. I need to amend the line

document.getElementById('imagePlaceHolder');

to point to the HTML file containing object to manipulate.

Can anyone advise me of the correct syntax please?

4

1 回答 1

1

在 HTML 文件中,您需要在标头中链接 javascript 文件

例如

<head>
<script src="/scripts/yourjavascript.js" type="text/javascript"></script>
</head>

然后在你的javascript文件顶部做一个onload函数

    window.onload = function(){
     changeImage("imgName", "descriptiveText");
    }

function changeImage(imgName,descriptiveText)
    {
        image = document.getElementById('imagePlaceHolder');
        image.src = imgName;

        text = document.getElementById('descriptionPlaceHolder');
        text.innerHTML=descriptiveText;
    }

任何使用的 javascriptdocument都应该引用 html 文档

于 2013-10-08T12:57:01.343 回答