JavaScript - onClick 获取被点击按钮的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4825295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - onClick to get the ID of the clicked button
提问by Bin Chen
How do find the id of the button which is being clicked?
如何找到被点击的按钮的 id?
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
}
回答by shamittomar
You need to send the ID as the function parameters. Do it like this:
您需要将 ID 作为函数参数发送。像这样做:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
This will send the ID this.id
as clicked_id
which you can use in your function. See it in action here.
这将发送IDthis.id
作为clicked_id
您可以在您的函数中使用。在这里查看它的实际效果。
回答by Jason LeBrun
In general, things are easier to keep organized if you separate your code and your markup. Define all of your elements, and then in your JavaScript section, define the various actions that should be performed on those elements.
一般来说,如果将代码和标记分开,事情会更容易组织起来。定义所有元素,然后在 JavaScript 部分中定义应对这些元素执行的各种操作。
When an event handler is called, it's called within the context of the element that was clicked on. So, the identifier thiswill refer to the DOM element that you clicked on. You can then access attributes of the element through that identifier.
当事件处理程序被调用时,它在被点击的元素的上下文中被调用。因此,this的标识符将引用您单击的 DOM 元素。然后,您可以通过该标识符访问元素的属性。
For example:
例如:
<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>
<script type="text/javascript">
var reply_click = function()
{
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>
回答by Prateek
USING PURE JAVASCRIPT: I know it's late but may be for the future people it can help:
使用纯 JAVASCRIPT:我知道现在已经晚了,但可能对未来的人有帮助:
In the HTML part:
在 HTML 部分:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
In the Javascipt Controller:
在 Javascipt 控制器中:
function reply_click()
{
alert(event.srcElement.id);
}
This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.
这样我们就不必在调用 javascript 函数时绑定 Element 的 'id'。
回答by sdleihssirhc
(I think the id
attribute needs to start with a letter. Could be wrong.)
(我认为该id
属性需要以字母开头。可能是错误的。)
You could go for event delegation...
你可以去事件委托...
<div onClick="reply_click()">
<button id="1"></button>
<button id="2"></button>
<button id="3"></button>
</div>
function reply_click(e) {
e = e || window.event;
e = e.target || e.srcElement;
if (e.nodeName === 'BUTTON') {
alert(e.id);
}
}
...but that requires you to be relatively comfortable with the wacky event model.
...但这需要您对古怪的事件模型相对适应。
回答by Mohanraj
<button id="1" onClick="reply_click(this)"></button>
<button id="2" onClick="reply_click(this)"></button>
<button id="3" onClick="reply_click(this)"></button>
function reply_click(obj)
{
var id = obj.id;
}
回答by Jay
<button id="1" class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>
<script>
$('.clickMe').click(function(){
alert(this.id);
});
</script>
回答by Timo Huovinen
How to do it without inline JavaScript
如何在没有内联 JavaScript 的情况下做到这一点
it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it.
Here is my way of attaching events to buttons.
I'm not entirely happy with how much longer the recommended method is compared to a simple onClick
attribute.
通常建议避免内联 JavaScript,但很少有示例说明如何做到这一点。
这是我将事件附加到按钮的方法。
我对推荐的方法与简单onClick
属性相比有多长并不完全满意。
2014 browsers only
仅限 2014 浏览器
<button class="btn">Button</button>
<script>
let OnEvent = (doc) => {
return {
on: (event, className, callback) => {
doc.addEventListener('click', (event)=>{
if(!event.target.classList.contains(className)) return;
callback.call(event.target, event);
}, false);
}
}
};
OnEvent(document).on('click', 'btn', function (e) {
window.console.log(this, e);
});
</script>
2013 browsers only
仅限 2013 浏览器
<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
var hasClass = function(el,className) {
return el.classList.contains(className);
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script>
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Cross-browser
跨浏览器
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Cross-browser with jQuery
使用 jQuery 跨浏览器
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
$(document).on('click', '.click-me', function(e){
doSomething.call(this, e);
});
})(jQuery);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.
您可以在文档准备好之前运行它,单击按钮将起作用,因为我们将事件附加到文档。
Here is a jsfiddle
For some strange reason the insertHTML
function does not work in it even though it works in all my browsers.
这是一个jsfiddle
由于某种奇怪的原因insertHTML
,即使它在我所有的浏览器中都可以使用,该函数也无法在其中运行。
You can always replace insertHTML
with document.write
if you don't mind it's drawbacks
您可以随时更换insertHTML
使用document.write
,如果你不介意它的缺点
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>
Sources:
资料来源:
回答by A-Sharabiani
If you don't want to pass any arguments to the onclick function, just use event.target
to get the clicked element:
如果您不想将任何参数传递给 onclick 函数,只需使用event.target
来获取被点击的元素:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
// event.target is the element that is clicked (button in this case).
console.log(event.target.id);
}
回答by codercat
With pure javascript you can do the following:
使用纯 javascript,您可以执行以下操作:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
check it On JsFiddle
在JsFiddle 上检查
回答by user3262563
You can simply do it this way:
你可以简单地这样做:
<input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
<script type="text/javascript">
function showId(obj) {
var id=obj;
alert(id);
}