简体   繁体   中英

updating variable from js file in an html file

I have some js code that has been imported from another file which has a variable in it I want to update in my HTML file. How can I update the variable without pasting the js code into my HTML file?

JS (script.js):

var link = "https://example.com"
var codeBlock = `...some html code... ${link} ...some more html code`;

document.getElementById("div").innerHTML = codeBlock

HTML:

<div id="div"></div>
<script src= "script.js"></script>
<script>
    //I want to change this variable
    var link = "https://anotherexample.com"
</script>

On line one of your code, you declare link and give it a value.

On line two, you use that value.

You can't change link later on and affect what happened when the value was read and used in the past.

If you want to change the final result, then it is the final result you have to change (ie you need to assign a new value to document.getElementById("div").innerHTML ).

You are getting the value but not setting it to the variable that the HTML is showing.Is this you are looking for :

 var updatedLink = document.getElementById("anotherlink").innerHTML; var codeBlock = `...some html code... ${updatedLink} ...some more html code`; document.getElementById("div").innerHTML = codeBlock 
 <div id="div"></div> <div id="anotherlink" style="display:none"></div> <script src= "script.js"></script> <script> var link = "https://anotherexample.com"; document.getElementById("anotherlink").innerHTML = link </script> 

Your script is working and the variable is being changed. If you console.log(link) after declaring it again, you'll see the variable has changed. If you're expecting the script to execute again, that won't happen without calling it again.

What you may want to try is iterating through the document looking for something to trigger that statement, for example, links in the document.

 const links = document.querySelectorAll('a'); var href = []; links.forEach(link => href.push(link.href)); var codeBlock = ''; href.forEach(link => { if (link == "https://stacksnippets.net/anotherexample.com") { codeBlock = `...some html code... ${link} ...some more html code`; document.getElementById('div').innerHTML = codeBlock; } }) 
 <div id="div"><a href="anotherexample.com">link</a></div> 

Or without checking for a specific URL:

 const links = document.querySelectorAll('a'); var href = []; links.forEach(link => href.push(link.href)); var codeBlock = ''; href.forEach(link => { codeBlock = `...some html code... ${link} ...some more html code`; document.getElementById('div').innerHTML = codeBlock; }) 
 <div id="div"><a href="anotherexample.com">link</a></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