// Event setup using a convenience method
$("p").click(function () {
console.log("You clicked a paragraph!");
});
// Equivalent event setup using the `.on()` method
$("p").on("click", function () {
console.log("click");
});
// Multiple events, same handler
$("input").on(
"click change", // Bind handlers for multiple events
function () {
console.log("An input was clicked or changed!");
}
);
// Binding multiple events with different handlers
$("p").on({
"click": function () {
console.log("clicked!");
},
"mouseover": function () {
console.log("hovered!");
}
});
$(document).ready(function () {
// Sets up click behavior on all button elements with the alert class
// that exist in the DOM when the instruction was executed
$("button.alert").on("click", function () {
console.log("A button with the alert class was clicked!");
});
// Now create a new button element with the alert class. This button
// was created after the click listeners were applied above, so it
// will not have the same click behavior as its peers
$("<button class=‘alert‘>Alert!</button>").appendTo(document.body);
});
// Event setup using the `.on()` method with data
$("input").on(
"change",
{foo: "bar"}, // Associate data with event binding
function (eventObject) {
console.log("An input value has changed! ", eventObject.data.foo);
}
);
var $element = $(this);
// Tearing down all click handlers on a selection
$("p").off("click");
// Tearing down a particular click handler, using a reference to the function
var foo = function () {
console.log("foo");
};
var bar = function () {
console.log("bar");
};
$("p").on("click", foo).on("click", bar);
$("p").off("click", bar); // foo is still bound to the click event
// Switching handlers using the `.one()` method
$("p").one("click", firstClick);
function firstClick() {
console.log("You just clicked this for the first time!");
// Now set up the new handler for subsequent clicks;
// omit this step if no further click responses are needed
$(this).click(function () {
console.log("You have clicked this before!");
});
}
// Using .one() to bind several events
$("input[id]").one("focus mouseover keydown", firstEvent);
function firstEvent(eventObject) {
console.log("A " + eventObject.type + " event occurred for the first time on the input with id " + this.id);
}
[DOM Event Learning] Section 3 jQuery事件处理基础 on(), off()和one()方法使用
原文:http://www.cnblogs.com/liu-Gray/p/4810367.html