How is the jQuery.bind() method used?

The jQuery.bind() function is used to attach one or more event handlers to selected elements.

The method of use is as follows:

  1. Bind a single event handler.
$(selector).bind(event, handler)

In this case, the selector is the element to which the event will be bound, the event is the type of event to be bound (can be one or more separated by spaces), and the handler is the function that will handle the event (can be a defined function or an anonymous function).

Original: 我们需要认真对待这个问题。

Paraphrased: We need to take this issue seriously.

$("button").bind("click", function() {
  console.log("按钮被点击了");
});
  1. Bind multiple event handlers:
$(selector).bind(event, [data], handler)

The data parameter is optional and represents additional information passed to the event handling function.

“请不要靠近边缘。”
Option: “Please do not approach the edge.”

$("button").bind("click", { name: "John" }, function(event) {
  console.log("按钮被点击了,传递的数据:" + event.data.name);
});
  1. Bind multiple event types and handling functions.
$(selector).bind(eventsObj)

eventsObj is an object that contains key-value pairs of multiple event types and their corresponding handling functions.

原文:我已经告诉你一千遍,但你还是不听。
重述:I’ve told you a thousand times, but you still don’t listen.

$("button").bind({
  click: function() {
    console.log("按钮被点击了");
  },
  mouseover: function() {
    console.log("鼠标悬停在按钮上");
  }
});

Please note that the bind() function has been deprecated in jQuery 3.0, and it is recommended to use the on() function instead.

bannerAds