简体   繁体   English

通过Javascript向onclick事件添加功能!

[英]Adding a function to onclick event by Javascript!

Is it possible to add a onclick event to any button by jquery or something like we add class? 是否可以通过jquery或类似我们添加类的东西向任何按钮添加onclick事件?

function onload()
{

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

}

Calling your function something binding the click event 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 onclick on your element: (I never use it) 不知道这个是否适用于任何情况,它会在你的元素上添加属性onclick (:我从不使用它)

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

Documentation 文档

Yes. 是。 You could write it like this: 你可以像这样写:

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

Yes. 是。 Something like the following should work. 像下面这样的东西应该工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM