繁体   English   中英

单击按钮后如何从按钮中获取值

[英]How to get value from button after it has been clicked

我正在努力完成这项任务:将事件侦听器固定到按钮上。 创建一个在单击其中一个按钮时调用的函数。 用 console.log 检查一下。 确保点击事件传递给这个函数。 确保您可以访问在此函数中单击的按钮的值。 用 console.log 检查一下。 单击时您希望在控制台中看到的结果是:Leopard / Lion / Elephant / Rhino 或 Buffalo。

fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
    fiveButtons[i].addEventListener("click", function () {
        
        Array.from(fiveButtons).forEach(function (nameButton) {
            console.log(nameButton.innerHTML);
        })
    });
}

这是我到目前为止所写的。 当我现在单击按钮时,结果是来自所有按钮的文本。 虽然我希望在单击按钮 Lion 后结果仅为“Lion”。

<h1>The Big Five</h1>
    <ul class="big-five-list">
       <li class="big-five-list-item">
           <button class="big-five-button">Lion</button>
       </li> etc.

您可以更改按钮以包含如下所示的 onclick 功能:

https://www.w3schools.com/jsref/event_onclick.asp

 <!DOCTYPE html> <html> <body> <button onclick="myFunction('Lion')">Lion</button> <input type="text" value="" id="getValue"> <p id="demo"></p> <script> function myFunction(value) { document.getElementById("getValue").value = value; } </script> </body> </html>

然后 onclick 函数将在 () 中有一个函数名称的值。 这会将您想要的值传递给函数,并且可以随心所欲地调用它。 上面的代码片段显示了如何使用它的示例

fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
    fiveButtons[i].addEventListener("click", function () {
        
        console.log(fiveButtons[i].innerHTML)
    });
}

试试这个解决方案!

fiveButtons = document.getElementsByClassName("big-five-button");
    for (var i = 0; i < fiveButtons.length; i++) {
        fiveButtons[i].addEventListener("click", function (item) {
       console.log(item.target.innerHTML);
        });
    }

创建 addEventListener 时,您可以使用事件对象来定位单击的元素,如下所示:

fiveButtons[i].addEventListener("click", function (event) {
       console.log(event.target.innerHTML);
    });

您传递给addEventListener的函数提供了一个事件参数:

fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
    fiveButtons[i].addEventListener("click", function (event) { // use the first argument
        console.log('element value:', event.target.value); // log the 'value' of the event target;
        // I suspect you want the innerHTML or innerText
        console.log('element innerText:', event.target.innerText);
    });
}

然后就可以从 event.target 中的 DOM 节点获取所需的信息

您不需要 for 循环内的 Array.from。 你可以这样做:

fiveButtons = document.getElementsByClassName("big-five-button");
for (let i = 0; i < fiveButtons.length; i++) {
    fiveButtons[i].addEventListener("click", function () {
        console.log(fiveButtons[i].innerText);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM