如何检查在一个事件中触发了哪个元素?

时间:2018-02-21 06:41:07

标签: javascript jquery

我有两个按钮,它运行相同的脚本,但创建不同的参数。

<input type='button' id='btn_a' value='button_a' /><br />
<input type='button' id='btn_b' value='button_b' /><br />

如何设置按钮为每个按下的按钮创建参数?也许这样的事情。

$('#btn_a, #btn_b').on('click', function(){
     if( $('#btn_a').data('clicked', true)) {
        //Create parameter for button A
    }

    if( $('#btn_b').data('clicked', true)) {
        //Create parameter for button B
    }

    //script for sent the parameters
});

2 个答案:

答案 0 :(得分:1)

您可以比较点击的 .page { width: 1000px; margin: auto; } .side_left{ width:650px; } .sidebar { float: right; width: 300px; height: 420px; margin-top:20px; background: red; } .content { padding-right: 20px; } article { background: #cdcdcd; padding: 15px; width:100%; margin-bottom: 20px; } h3 { margin: 0; } .buttons { display: flex; justify-content: space-between; } <div class="page"> <div class="sidebar"></div> <div class="content"> <div class="side_left"> <article> <h3>Lorem, ipsum dolor.</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos non nostrum distinctio officia aliquid maxime doloremque harum id consequuntur quo.</p> <div class="buttons"> <button>btn1</button> <button>btn2</button> </div> </article> <article> <h3>Lorem, ipsum dolor.</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos non nostrum distinctio officia aliquid maxime doloremque harum id consequuntur quo.</p> <div class="buttons"> <button>btn1</button> <button>btn2</button> </div> </article> <article> <h3>Lorem, ipsum dolor.</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos non nostrum distinctio officia aliquid maxime doloremque harum id consequuntur quo.</p> <div class="buttons"> <button>btn1</button> <button>btn2</button> </div> </article> </div> <article> <h3>Lorem, ipsum dolor.</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos non nostrum distinctio officia aliquid maxime doloremque harum id consequuntur quo.</p> <div class="buttons"> <button>btn1</button> <button>btn2</button> </div> </article> <article> <h3>Lorem, ipsum dolor.</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos non nostrum distinctio officia aliquid maxime doloremque harum id consequuntur quo.</p> <div class="buttons"> <button>btn1</button> <button>btn2</button> </div> </article> <article> <h3>Lorem, ipsum dolor.</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos non nostrum distinctio officia aliquid maxime doloremque harum id consequuntur quo.</p> <div class="buttons"> <button>btn1</button> <button>btn2</button> </div> </article> </div> </div>

id

button

即。使用switch-case执行按钮特定操作

&#13;
&#13;
this.id === "btn_a"
&#13;
event.currentTarget.id == "btn_a"
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$('#btn_a, #btn_b').on('click', function(e){
   alert(e.target.id);
});

这应该有用,并为您提供元素(目标)ID。