Home  >  Article  >  Web Front-end  >  Problems using delegate in jQuery_jquery

Problems using delegate in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:51:331024browse

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)

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>

我老写成了

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

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

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

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

Statement:
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