【问题标题】:In Javascript multiple onclick(); Collect Date and Single function在 Javascript 中多个 onclick();收集日期和单次功能
【发布时间】:2020-10-14 04:55:04
【问题描述】:

function t1() {
        var show1 = document.getElementById("p1").innerHTML;
        window.alert(show1)
}

function t2() {
        var show2 = document.getElementById("p2").innerHTML;
        window.alert(show2)
}

function t3() {
        var show3 = document.getElementById("p3").innerHTML;
        window.alert(show3)
}
<div>

<p id="p1">I am Headign 1</p>
<p id="p2">I am Headign 2</p>
<p id="p3">I am Headign 3</p>

</div>





<button onclick="t1();">Bt 1</button>
<button onclick="t2();">Bt 2</button>
<button onclick="t3();">Bt 3</button>

在这个程序中,有3个函数用于运行类似的程序。如何只使用一个函数并获取我在这个程序中提到的所有信息。

【问题讨论】:

    标签: javascript performance onclick dom-events


    【解决方案1】:

    试试这个解决方案

    <script type = "test/javascript">
        function t(i) {
            let show = document.getElementById("p" + i).innerHTML;
            window.alert(show);
        }
    </script>
    
    
    
    <button onclick="t(1);">Bt 1</button>
    <button onclick="t(2);">Bt 2</button>
    <button onclick="t(3);">Bt 3</button>
    

    【讨论】:

    • i - 是函数 t 的参数。单击时,您可以使用参数调用此函数。在函数中,您将此参数用作元素 id 的一部分
    【解决方案2】:

    你可以使用事件委托来做到这一点,这样你就不需要&lt;p&gt;元素的id,并且请不要写内联JS它有很多缺点

    /* the onclick event can be delegated so you can have only one 
     * listener for the parent element */
    document.querySelector("div").onclick = function(e) {
      // alert the innerHTML only if the element is a `<p>`
      e.target.nodeName === "P" && alert(e.target.innerHTML);
    }
    <div>
      <p>I am Headign 1</p>
      <p>I am Headign 2</p>
      <p>I am Headign 3</p>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多