简体   繁体   中英

How do i connect javascript arrays with html file?

var programming_languages = [
    "python",
    "javascript",
    "mongodb",
    "json",
    "java",
    "html",
    "css",
    ]
function randomWord() {
  answer = programming_languages[Math.floor(Math.random() * programming_languages.length)];
}

Im complete beginner and this is not my code, so my question is how to make function with if statement that will write something in htlm when certain word in array gets picked. What i did was

<script>
 function updateWord(){
            if(programming_languages == [0]){
                document.write("<h1>something<h1/>");
                }
        }
<script/>

In this case what im trying to do is when word "python" gets picked that html inputs something Thank you regards

Sounds like your updateWord function is not being called.

I'm guessing you have a select element to pick the language from?

Check out the document here to hook up an event listener to your select statement: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

I inserted the working code into this answer.

 const selectElement = document.querySelector('.ice-cream'); selectElement.addEventListener('change', (event) => { const result = document.querySelector('.result'); result.textContent = `You like ${event.target.value}`; });
 <label>Choose an ice cream flavor: <select class="ice-cream" name="ice-cream"> <option value="">Select One …</option> <option value="chocolate">Chocolate</option> <option value="sardine">Sardine</option> <option value="vanilla">Vanilla</option> </select> </label> <div class="result"></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