jQuery保存上下文onclick
jQuery save context onclick
是否在元素的子元素上绑定一个单击侦听器,同时仍然将$(this)
上下文指向该子元素的固定父元素?比如说我有一个页面-
<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了。
相关文章:
- 将函数的上下文应用于javascript变量
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 如何在执行此特定onclick事件时执行JavaScript函数
- 使用JQuery的动态上下文菜单
- Setting default onclick behavior for <img> tag in gene
- Javascript全局onclick监听器
- 如何调用“;链接_;在onclick事件上使用Javascript
- onclick函数需要双击,因为类分配延迟
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 使用onclick绘制SVG路径
- 如何访问UIWebView'的子窗口上下文
- 如何将数据从onclick按钮传递到变量
- 选择onclick事件jquery
- I'我设计了一个下拉菜单,onclick会出现,而on blur会消失
- 如何刷新列表框内容onclick或blur事件
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 使用' onclick '与上下文菜单子项目
- dojo EnhancedGrid上下文菜单-如何从菜单项获取rowIndex 's onclick事件
- Chrome扩展>上下文菜单Api >无法添加onclick处理程序
- jQuery保存上下文onclick