search
HomeWeb Front-endJS TutorialIn-depth analysis of the usage of .live() method in jQuery_jquery

给jquery动态生成的页面元素添加事件?使用livequery插件,或可以使用jquery的live方法。摘录一段live简单使用方法。

更多详情还见官网 http://api.jquery.com/live/

live(type, [data],fn)

概述

jQuery给所有匹配的元素附加一个事件处理函数,即使这个元素是以后再添加进来的也有效。

这个方法是基本是的 .bind() 方法的一个变体。使用 .bind()时,选择器匹配的元素会附加一个事件处理函数,而以后再添加的元素则不会有。为此需要再使用一次 .bind() 才行。比如说

Click here
 
可以给这个元素绑定一个简单的click事件:

$('.clickme').bind('click', function() {
 alert("Bound handler called.");     
}); 

当点击了元素,就会弹出一个警告框。

然后,想象一下这之后有另一个元素添加进来了。

$('body').append('
Another target
');

尽管这个新的元素也能够匹配选择器".clickme" ,但是由于这个元素是在调用 .bind() 之后添加的,所以点击这个元素不会有任何效果。

.live()就提供了对应这种情况的方法。如果我们是这样绑定click事件的:

$('.clickme').live('click', function() {
 alert("Live handler called.");      
});

然后再添加一个新元素:

$('body').append('
Another target
');

然后再点击新增的元素,他依然能够触发事件处理函数。 

事件委托

.live()方法能对一个还没有添加进DOM的元素有效,是由于使用了事件委托:绑定在祖先元素上的事件处理函数可以对在后代上触发的事件作出回应。

传递给 .live()的事件处理函数不会绑定在元素上,而是把他作为一个特殊的事件处理函数,绑定在 DOM树的根节点上。在我们的例子中,当点击新的元素后,会依次发生下列步骤:

1、生成一个click事件传递给

来处理

2、由于没有事件处理函数直接绑定在

上,所以事件冒泡到DOM树上

3、事件不断冒泡一直到DOM树的根节点,默认情况下上面绑定了这个特殊的事件处理函数。

4、执行由 .live() 绑定的特殊的click 事件处理函数。

5、这个事件处理函数首先检测事件对象的target 来确定是不是需要继续。这个测试是通过检测 $(event.target).closest('.clickme')能否找到匹配的元素来实现的。

6、如果找到了匹配的元素,那么调用原始的事件处理函数。

由于只有在事件发生时才会在上面的第五步里做测试,因此在任何时候添加的元素都能够响应这个事件。


附加说明

.live()虽然很有用,但由于其特殊的实现方式,所以不能简单的在任何情况下替换 .bind()。主要的不同有:

在jQuery 1.4中,.live()方法支持自定义事件,也支持所有的JavaScript 事件。在jQuery 1.4.1中,甚至也支持 focus 和 blue事件了(映射到更合适,并且可以冒泡的focusin和focusout上)。

另外,在jQuery1.4.1中,也能支持hover(映射到"mouseenter mouseleave")。然而在jQuery1.3.x中,只支持支持的JavaScript事件和自定义事件:click, dblclick, keydown, keypress,keyup, mousedown, mousemove, mouseout, mouseover, 和 mouseup.

.live()并不完全支持通过DOM遍历的方法找到的元素。取而代之的是,应当总是在一个选择器后面直接使用 .live()方法,正如前面例子里提到的。

当一个事件处理函数用 .live()绑定后,要停止执行其他的事件处理函数,那么这个函数必须返回 false。 仅仅调用 .stopPropagation()无法实现这个目的。

参考 .bind() 方法可以获得更多关于事件绑定的信息。

在jQuery 1.4.1中,你可以一次绑定多个事件给 .live() ,跟.bind() 提供的功能类似。

在jQuery 1.4中,data参数可以用于把附加信息传递给事件处理函数。一个很好的用处是应付由闭包导致的问题。可以参考 .bind()的讨论来获得更多信息。


参数

typeString Event type

data (optional) Object The event handler function to be bound

fn Function The event processing function to be bound


Example

HTML code:

Click me!

jQuery code:
$("p").live("click", function(){
$(this).after("

Another paragraph!

");
});

Description:

Prevent default event behavior and event bubbling, return false

jQuery code:
$("a").live("click", function() { returnfalse; });

Description:

Only prevents default event behavior

jQuery code:
$("a").live("click", function(event){
event.preventDefault();
});

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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools