简体   繁体   中英

Calling Document Object in Separate JS File?

I'm guessing this is a stupid question but I'm having a lot of trouble with this simple function:

--Sits in.js file--

function GetAssets() {
    alert("Hello World!");
    document.getElementById("asset_summary").innerHTML = "Test";
}

--sits in html.erb file--

<script type="text/javascript" src="jslogic/overview_summary.js"></script>
<script>GetAssets();</script>

I know the function call works b/c I can comment out the document.getElementByID line and then get an alert. I know the document.getElementByID works because I can copy/paste it into a script tag and it runs. So something must change in the syntax when you move this call to an external file? I'm sure this is easy but I can't find the right reference to fix it. Thanks in advance!

Clarifying the buried question: this function doesn't run properly and I'm assuming it's because of the document.getElementByID attribute on line 3 - if it is, could someone explain how I need to change this? If it's not, can someone explain why this works within the html script tags but not as a separate function?

First of all please rename your function GetAssets() to getAssets()

Rule of thumb: function names should be camelCase. PascalCase are for class names. Read JavaScript naming convention to learn more.

In your javascript file you declared your function but you never invoked it.

//Goes in your javascript file
function getAssets() {
    alert("Hello World!")
}
//Invoke the function
//getAssets()
//is commented so we can use a button in the html file to call the function

Then in your HTML file just remove the line: <script>GetAssets();</script>

But if you want to run your function from the html you can use a button for it.

<button onClick="getAssets()">Get Assets</button>

All this is assuming that your html and your javascript files are linked correctly.


 function getAssets() { alert("Hello World;"). let divAssets = document.getElementById("asset_summary") divAssets.innerHTML = "<h3>Test</h3>" }
 <div> <h1>hola mundo</h1> <button onClick="getAssets()">Get Assets</button> <br /> <div id="asset_summary"> <h1>Sumary 1</h1> </div> </div>

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