获得哪一个键被按下了

对于下面的html


    <div id="buttons">

        <button order="1" onclick="showImg()">1</button>

        <button order="2" onclick="showImg()">2</button>

        <button order="3" onclick="showImg()">3</button>

        <button order="4" onclick="showImg()">4</button>

        <button order="5" onclick="showImg()">5</button>

    </div>


我需要在某个button被按下的时候,js 得到它的order ,如何做到?


至尊宝的传说
浏览 365回答 3
3回答

郎朗坤

const&nbsp;order&nbsp;=&nbsp;event.target.getAttribute('order')

守着星空守着你

不建议把事件函数写在html页面,js获取可以这样:先遍历每个button,然后使用getAttribute函数获取自定义的属性值

慕尼黑8549860

&nbsp;<div id="buttons">&nbsp; &nbsp; &nbsp; &nbsp; <button order="1" onclick="showImg()">1</button>&nbsp; &nbsp; &nbsp; &nbsp; <button order="2" onclick="showImg(this)">2</button>&nbsp; &nbsp; &nbsp; &nbsp; <button order="3" onclick="showImg(this)">3</button>&nbsp; &nbsp; &nbsp; &nbsp; <button order="4" onclick="showImg(this)">4</button>&nbsp; &nbsp; &nbsp; &nbsp; <button order="5" onclick="showImg(this)">5</button>&nbsp; &nbsp; </div>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp;function showImg(e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let order = e.target.order;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; </script>&nbsp; &nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript