我想在单击活动的某些javascript时使用按钮吗?

时间:2019-03-05 08:42:08

标签: javascript

以下JS和HTML不起作用。当我单击按钮时,它应该只显示带有字母a的名称。另外,我想将onClick保留在javascript端。

var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"];

var result = names.filter(function(name) {
  return name.includes("a");

});

document.getElementById("btn").onclick = result;
<button id="btn">Get names with letter a</button>

1 个答案:

答案 0 :(得分:1)

var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"];
document.addEventListener('DOMContentLoaded', () => {

    document.getElementById("btn").addEventListener("click", () => {
        var result = names.filter(function (name) {
            return name.includes("a");
        });
        console.log(result)
    });
});
<button id="btn">Get names with letter a</button>

您应该在事件侦听器中进行过滤,并将其输出到控制台