我有4个按钮,当我点击任何按钮时,它会重定向到所有按钮的同一页面,我想知道用户在进入下一页之前按了哪个按钮,我一直在尝试,但找不到。
这是我的代码:
$( "#buttons" ).click(function() {
alert('button');
window.location.href = "score.html";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<div id="buttons">
<button type="button" id="button1">button 1</button>
<button type="button" id="button2">button 2</button>
<button type="button" id="button3">button 3</button>
<button type="button" id="button4">button 4</button>
</div>
你有什么想法
答案 0 :(得分:6)
click
启动的元素在传递到处理程序的事件对象上以target
形式提供,因此(但请参见下文):
// Accept the event arg -------v
$( "#buttons" ).click(function(e) {
alert('button: ' + e.target.id); // <=== Use e.target.id to get its ID
// window.location.href = "score.html"; (commented out for live demo)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<div id="buttons">
<button type="button" id="button1">button 1</button>
<button type="button" id="button2">button 2</button>
<button type="button" id="button3">button 3</button>
<button type="button" id="button4">button 4</button>
</div>
请注意,只要点击#buttons
div
,,即使它不在某个按钮上,它就会发出提醒。如果您只想点击按钮,则可以使用.on
的选择器仅在点击通过按钮时给您打电话。它会调用您的处理程序,就好像您已将处理程序直接挂钩到按钮一样,即使实际上您已将其挂钩到#button
div,因此我们使用this.id
作为ID:
$( "#buttons" ).on("click", "button", function() {
alert('button: ' + this.id);
// window.location.href = "score.html"; (commented out for live demo)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<div id="buttons">
<button type="button" id="button1">button 1</button>
<button type="button" id="button2">button 2</button>
<button type="button" id="button3">button 3</button>
<button type="button" id="button4">button 4</button>
</div>