jQuery保存上下文onclick

jQuery save context onclick

本文关键字:onclick 上下文 保存 jQuery      更新时间:2023-09-26

是否在元素的子元素上绑定一个单击侦听器,同时仍然将$(this)上下文指向该子元素的固定父元素?比如说我有一个页面-

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>

每当点击.clickabblelinkfromtheparent时,我想从.fixedClass中抓取data-important的值,而不使用.parent().parent().parent(),因为它们都不可靠-

JS:

$(".fixedClass .clickabblelinkfromtheparent").on("click",function(){alert($(this).parent().parent().data("important"));return false;});
http://jsfiddle.net/zcdSw/

我也试过了:

$(".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/和

$(".clickabblelinkfromtheparent", ".fixedClass").on("click",function(){alert($(this).context);return false;});
http://jsfiddle.net/Q8a67/1/

这些似乎都不起作用。那么,如何使用jQuery实现这一点呢?

你在尝试这样做吗?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'));
});

要检索DOM树中祖先的第一个重要的数据属性值,您可以基于以下代码片段构建一些内容:

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/

注意,使用这个方法,你不再需要fixedClass了。