search
HomeWeb Front-endJS TutorialDetailed explanation of the difference between target and currentTarget

Detailed explanation of the difference between target and currentTarget

Jun 17, 2017 pm 05:52 PM
the differenceDetailed explanation

2014-6-25

I read the jquery manual today and found that jQuery's event object module also has a currentTarget, which always points to this.

So the conclusion is: the native currentTarget and jQuery's currentTarget are completely different. We should focus on different treatment.

2014-6-17

What is the difference between target and currentTarget?

Easy to understand:

For example, there are A and B now,

A.addChild(B)

A listens to mouse click events

Then when B is clicked, the target is B and the currentTarget is A

That is to say, the currentTarget is always the one who listens to the event, and the target is the real sender of the event

Summary:

target is in the target stage of the event flow; currentTarget is in the capture, target and bubbling stages of the event flow. Only when the event flow is in the target stage, the two directions are the same. When it is in the capturing and bubbling stages, the target points to the clicked object and the currentTarget points to the object of the current event activity (usually the parent). class).

Conclusion: Due to the need to be compatible with IE browser, events are generally processed in the bubbling stage. At this time, the target and currentTarget are different in some cases.

The first place

function(e){
    var target = e.target || e.srcElement;//兼容ie7,8
    if(target){
        zIndex = $(target).zIndex();
    }
}

//往上追查调用处
enterprise.on(img,'click',enterprise.help.showHelp);

Use $(target).zIndex(); under IE7-8; you can get

Use $(e.currentTarget under IE7-8 ).zIndex(); cannot be obtained, it may be that there is neither target nor currentTarget under IE

Test it (of course in the IE browser)

<input>
<script> 
	btn1.attachEvent("onclick",function(e){
		alert(e.currentTarget);//undefined
		alert(e.target);       //undefined
		alert(e.srcElement);   //[object HTMLInputElement]
	});
</script>

Second Place:

$(element).on('click',jQuery.proxy(this, 'countdownHandler', this.name, this.nameAlert));
function countdownHandler(name, nameAlert){
    var _this = this,
    zIndex = 1999;//获取不到target时的默认值
    if(arguments[2] && arguments[2].currentTarget && $(arguments[2].currentTarget)){
        zIndex = $(arguments[2].currentTarget).zIndex();
        if(zIndex){
            zIndex += 1;
        }else{//获取不到z-index值
            zIndex = 1999;
        }
    }
}

Use $(arguments[2].currentTarget).zIndex(); you can also get

Estimated conclusion: The latter uses jquery to bind events , jQuery internally lets currentTarget represent the current element. Similar to target under FF/Chrome and srcElement under IE.

Online examples:

    <p>  
        click outer  
        </p><p>click inner</p>  
        <br>  
      
      
    <script>  
    function G(id){  
        return document.getElementById(id);      
    }  
    function addEvent(obj, ev, handler){  
        if(window.attachEvent){  
            obj.attachEvent("on" + ev, handler);  
        }else if(window.addEventListener){   
            obj.addEventListener(ev, handler, false);  
        }  
    }  
    function test(e){  
        alert("e.target.tagName : " + e.target.tagName + "/n e.currentTarget.tagName : " + e.currentTarget.tagName);  
    }  
    var outer = G("outer");  
    var inner = G("inner");  
    //addEvent(inner, "click", test);  // 两者都是P标签
    addEvent(outer, "click", test);  //结论:当在outer上点击时,e.target与e.currentTarget是一样的,都是p;当在inner上点击时,e.target是p,而e.currentTarget则是p。
    </script>

Objects this, currentTarget and target

are handled in events Inside the program, the object this is always equal to the value of currentTarget, while target only contains the actual target of the event. If the event handler is assigned directly to the target element, this, currentTarget, and target contain the same values. Take a look at the following example:

var btn = document.getElementById("myBtn");
btn.onclick = function (event) {
    alert(event.currentTarget === this); //ture
    alert(event.target === this); //ture
};

This example detects the values ​​of currentTarget, target and this. Since the target of the click event is the button, these three values ​​are equal at one time. If the event handler exists in the button's parent node, then these values ​​are not the same. Look at the following example again:

document.body.onclick = function (event) {
    alert(event.currentTarget === document.body); //ture
    alert(this === document.body); //ture
    alert(event.target === document.getElementById("myBtn")); //ture
};

When the button in this example is clicked, both this and currentTarget are equal to document.body because the event handler is registered to this element. However, the target element is equal to the button element, thinking that it is the real target of the click event. Since there is no event handler registered on the button, the click event bubbles up to document.body, where the event is handled.

When you need to handle multiple events through a function, you can use the type attribute. For example:

var btn = document.getElementById("myBtn");
var handler = function (event) {
        switch (event.type) {
        case "click":
            alert("Clicked");
            break;
        case "mouseover":
            event.target.style.backgroundColor = "red";
            bread;
        case "mouseout":
            event.target.style.backgroundColor = "";
            break;
        }
    };
btn.onclick = handler;
btn.onmouseover = handler;
btn.onmouseout = handler;

The above is the detailed content of Detailed explanation of the difference between target and currentTarget. For more information, please follow other related articles on the PHP Chinese website!

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.