Home > Web Front-end > JS Tutorial > Problems using delegate in jQuery_jquery

Problems using delegate in jQuery_jquery

WBOY
Release: 2016-05-16 15:51:33
Original
1073 people have browsed it

I'm used to bind and live, but I'm not used to delegate...

Support for binding events to dynamically generated tag elements may be live and delegate, but the new version no longer supports live, only delegate

Delegate is really special, different from other event binding styles.

I stumbled because I was used to the previous bind style.

To put it simply, it is carelessness.

The

delegate() method adds one or more event handlers to the specified element (a child element of the selected element) and specifies the function to run when these events occur.

Event handlers using the delegate() method apply to the current or future elements (such as new elements created by scripts).

Grammar

$(selector).delegate(childSelector,event,data,function)
Copy after login

Parameters Description
childSelector Required. Specifies one or more child elements to which event handlers are attached.
event

Required. Specifies one or more events to attach to the element.

Multiple event values ​​separated by spaces. Must be a valid event.

data 可选。规定传递到函数的额外数据。
function 必需。规定当事件发生时运行的函数。

比如这段小代码啊

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $("div").delegate("button","click",function(){
  $("p").slideToggle();
 });
});
</script>
</head>
<body>
<div style="background-color:red">
<p>这是一个段落。</p>
<button>请点击这里</button>
</div>

</body>
</html>

Copy after login

我老写成了

$(document).ready(function(){
 $("div").delegate($("button"),"click",function(){
  $("p").slideToggle();
 });
});
Copy after login

子选择器不需要选择起来了..

不然就像我那样出现不知名的错误(点击会触发click,但点击其他元素也会触发click...)

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template