如何通过没有id,class或jQuery的tagName获取按钮?

我想使用tagName获取不带id,class或jQuery的按钮文本,并将这些文本写入p标签。我的简单测试代码如下。希望您了解我正在尝试做的事情。


            <button>Button 1</button>

            <button>Button 2</button>

            <p id="result" ></p>



            <script type="text/javascript">

                function tagName(tag){

                    var buttons = document.getElementsByTagName(tag);

                    var totalButton = buttons.length;


                    for(var i=0;i<totalButton;i++){

                        // here i want to check which button clicked?

                    }


                };


                    tagName("button").onclick = function(){

                    document.getElementById("result").innerHTML = tagName("button").innerHTML;

                }

            </script>

您能帮我完成这段代码吗? 注意:我只有一个功能tagName()


慕桂英4014372
浏览 260回答 3
3回答

POPMUISE

<html><head>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function tagName(tag) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var buttons = document.getElementsByTagName(tag);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var totalButton = buttons.length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var r = []&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < totalButton; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // here i want to check which button clicked?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r.push(buttons[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return r;&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; function onLoad() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tagName("button").forEach(function (item, idx) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; item.addEventListener('click', function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("result").innerHTML = item.innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></head><body onload="onLoad()">&nbsp; &nbsp; <button>Button 1</button>&nbsp; &nbsp; <button>Button 2</button>&nbsp; &nbsp; <p id="result"></p>&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; </script></body></html>

ABOUTYOU

尝试这样的事情:var obj = document.getElementsByTagName("button");for (let item of obj) {&nbsp; item.onclick = function(){&nbsp; &nbsp; document.getElementById("result").innerHTML = item.innerHTML;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript