Reputation: 624
Let's assume I created one div inside of another one like this:
<div class='parent'>
Parent
<div class='chid'>
Child
</div>
</div>
And a javascript / jQuery script:
// Parent click event handler
$(document).on('click', '.parent', function(e){
console.log("Parent clicked");
console.log(myVar); // <--- undefined obviously.
});
// Child click event handler
$(document).on('click', '.child', function(e){
var myVar = "This is some string.";
console.log("Child clicked");
});
Now what I want to achieve is to pass the value of myVar from child click event handler to the parent click event handler, so that I can use that variable in the higher-level event handler?
Upvotes: 0
Views: 51
Reputation: 18322
One way, without having to make myVar
global, is this:
$(document).on("click", "#parent", function(e) {
console.log('clicked parent!', e.myVar); // if child was clicked, myVar will have value
});
$(document).on("click", "#child", function(e) {
var myVar = 12;
e.myVar = myVar; // attach de variable to the event
console.log('clicked child!');
});
You attach a value to the event that bubbles up the DOM, so you receive the value ONLY when the inner DIV is clicked.
I'm sure that, depending on what you wnat to achieve, there are better ways to do this, but, without more info, this should work.
Hope this helps you.
Upvotes: 2