简体   繁体   中英

jQuery save context onclick

Is there anyway to bind an click listener on a child of an element, while still pointing the $(this) context to a fixed parent of that child? For example so lets just say I had a page -

HTML:

<p><div data-important="idthatisneeded1" class="fixedClass">
<div id="dynamicallygeneratedfirstchild">
<div id="dynamicallygeneratedsecondchild">
<a class="clickabblelinkfromtheparent" href="#">Link1</a>
</div>
</div>
</div></p>
<p><div data-important="idthatisneeded2" class="fixedClass">
<div id="dynamicallygeneratedfirstchild">
<a class="clickabblelinkfromtheparent" href="#">Link2</a>
</div>
</div></p>

I want to grab the values of data-important from .fixedClass whenever .clickabblelinkfromtheparent is clicked, without using .parent().parent() or .parent() since they're both unreliable -

JS:

$(".fixedClass .clickabblelinkfromtheparent").on("click",function(){alert($(this).parent().parent().data("important"));return false;});

http://jsfiddle.net/zcdSw/

I've also tried:

$(".fixedClass .clickabblelinkfromtheparent").on("click",function(){alert($(this).context(".fixedClass").data("important"));return false;});

http://jsfiddle.net/zcdSw/1/

$(".clickabblelinkfromtheparent", ".fixedClass").on("click",function(){alert($(this).data("important"));return false;});

http://jsfiddle.net/Q8a67/ and

$(".clickabblelinkfromtheparent", ".fixedClass").on("click",function(){alert($(this).context);return false;});

http://jsfiddle.net/Q8a67/1/

None of which seems to work.. So how exactly is this achievable with jQuery?

are you trying something like this? jsfiddle: http://jsfiddle.net/zKp3P/

$(function(){
  $('.clickabblelinkfromtheparent').on('click', function(){
    //$(this).closest('.fixedClass').data('important');
    alert($(this).closest('.fixedClass').data('important'));
  });
});
$('.clickabblelinkfromtheparent').on('click', function(){
    alert($(this).closest('.fixedClass').data('important'));
});

To retrieve the first data-important attribute value of an ancestor in the DOM tree, you can tree something based on this snippet :

function searchDataInParentAxe($child, key) {
  var parent = $child.parent();
  return parent.data(key) || searchDataInParentAxe(parent, key);
}

$(".clickabblelinkfromtheparent").on("click", function () {
  alert(searchDataInParentAxe($(this), 'important'));
  return false;
});

http://jsfiddle.net/zoom/2mhSQ/

Note that with this method you don't need the fixedClass anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM