【问题标题】:Problem when linking onclick button with a simple JS function将 onclick 按钮与简单的 JS 函数链接时出现问题
【发布时间】:2021-10-10 17:11:31
【问题描述】:

我一直在尝试将一些 HTML/CSS 功能应用到您在下面看到的简单 JS 代码中,其中包括基于两个数组返回一个随机句子。

我想创建一个简单的 onclick 按钮来显示生成的句子,但我仍然无法让它工作。你有什么想法或线索吗?我已经设法用变量/文本完成了它,但是在访问函数时我遇到了一些问题,这当然是程序的重点。

提前感谢大家的帮助。

JS:

const personArr = ["Father Burgundy", "Constable Grey"];
const locationArr = ["the sauna", "the larder"];

const selectArr = (array) => {
 return(array[Math.floor(Math.random()*array.length)]);
}

const createMessage = () => {
 const message = "It was " + selectArr(personArr) + " in " + selectArr(locationArr)"!";
 return message;
};

const init = () => {
 const message = createMessage();
 console.log(message);
};

init();

----------------------------

function demo() {
 document.getElementById("output").innerHTML = init();
}

HTML:

<button id="btn" onclick="demo()">Click here!</button>
<p id="output"></p>

【问题讨论】:

  • 您的init() 函数应该返回“输出”元素的实际内容。现在它什么也不返回。您是否像在createMessage() 中那样尝试过return message;

标签: javascript html button onclick


【解决方案1】:

您只需要从 init() 函数返回值,所以这是一个工作 jsfiddle。

https://jsfiddle.net/vuks89/2cy1fbkd/

const init = () => {
 const message = createMessage();
 console.log(message);
 return message;
};

另外,我不确定为什么在定义后需要调用init();。 如果只是为了这个用例,它可能是不必要的,因为一旦按钮被点击,它就会被调用。

【讨论】:

    【解决方案2】:

    在 init() 中返回消息并在最后一个字符串 i createMessage() 之前添加 +

    const personArr = ["Father Burgundy", "Constable Grey"];
    const locationArr = ["the sauna", "the larder"];
    
    const selectArr = (array) => {
     return(array[Math.floor(Math.random()*array.length)]);
    }
    
    const createMessage = () => {
     const message = "It was " + selectArr(personArr) + " in " + selectArr(locationArr) + "!";
     return message;
    };
    
    const init = () => {
     const message = createMessage();
     console.log(message);
      return message;
    };
    
    function demo() {
     document.getElementById("output").innerHTML = init();
    }
    <button id="btn" onclick="demo()">Click here!</button>
    <p id="output"></p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-07
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      相关资源
      最近更新 更多