通过 Javascript 向 onclick 事件添加函数!

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3220006/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:43:58  来源:igfitidea点击:

Adding a function to onclick event by Javascript!

javascriptjqueryonclick

提问by esafwan

Is it possible to add a onclickevent to any button by jquery or something like we add class?

是否可以onclick通过 jquery 或类似我们添加类的东西向任何按钮添加事件?

function onload()
{

//add a something() function to button by id

}

回答by BrunoLM

Calling your function somethingbinding the clickevent on the element with a ID

调用您的函数something绑定click带有 ID 的元素上的事件

$('#id').click(function(e) {
    something();
});

$('#id').click(something);

$('#id').bind("click", function(e) { something(); });

Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).

Live 略有不同,它会为添加的任何元素绑定事件,但由于您使用的是 ID,它可能不会发生,除非您从 DOM 中删除该元素并稍后重新添加(使用相同的 ID)。

$('#id').live("click", function(e) { something(); });

Not sure if this one works in any case, it adds the attribute onclickon your element: (I never use it)

不确定这在任何情况下是否有效,它会onclick在您的元素上添加属性:(我从不使用它)

$('#id').attr("onclick", "something()");

Documentation

文档

回答by Ken Earley

Yes. You could write it like this:

是的。你可以这样写:

$(document).ready(function() {
  $(".button").click(function(){
    // do something when clicked
  });
});

回答by Jason McCreary

Yes. Something like the following should work.

是的。像下面这样的东西应该可以工作。

$('#button_id').click(function() {
  // do stuff
});

回答by melhosseiny

$('#id').click(function() {
    // do stuff
});