【问题标题】:How do i connect javascript arrays with html file?如何将 javascript 数组与 html 文件连接?
【发布时间】:2020-03-27 02:21:04
【问题描述】:
var programming_languages = [
    "python",
    "javascript",
    "mongodb",
    "json",
    "java",
    "html",
    "css",
    ]
function randomWord() {
  answer = programming_languages[Math.floor(Math.random() * programming_languages.length)];
}

我是初学者,这不是我的代码,所以我的问题是如何使用 if 语句创建函数,当数组中的某个单词被选中时,该函数将在 htlm 中写入一些内容。 我所做的是

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

在这种情况下,我试图做的是当单词“python”被选中时,html 输入了一些东西 谢谢问候

【问题讨论】:

  • 欢迎来到 Stack Overflow!不是很清楚你在问什么。您应该查看how to ask,然后点击问题底部的编辑按钮。

标签: javascript html arrays if-statement


【解决方案1】:

听起来你的 updateWord 函数没有被调用。

我猜你有一个选择元素来选择语言?

在此处查看文档以将事件侦听器连接到您的 select 语句:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

我在这个答案中插入了工作代码。

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>

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 2012-11-24
    • 2021-04-25
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多