致所有人:如果我没有理解StackOverflow的协议,很抱歉。我会立即努力纠正我在社区中的地位。话虽如此:
我正在尝试更改jQuery函数的上下文,这取决于调用它的内容。在下面的代码中,当页面第一次加载时,我们看到调用limitDates()函数时使用了HTMLElementDiv作为当前上下文。当我们通过在输入字段中输入来调用它时,我们看到它不是一个div,但是尝试使用$(This) div (‘.closest’)获取父div会返回一个HTMLElementInput,而不是div。有什么想法吗?
更新:创建了一个小提琴:http://jsfiddle.net/earachefl/XBFNQ/8/
<script type="text/javascript" src="common/js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="common/js/jquery-ui-1.8.12.custom.min.js" ></script>
<div class="datemodule">
<input class="date_from" type="text" id="date_from_#name#" name="date_from" value=#start#>
</div>
<script>
$(document).ready(function(){
$('div.datemodule').limitDates();
$('.date_from').keydown(function(){
$(this).limitDates();
});
});
(function($){
$.fn.limitDates = function(){
return this.each(function(){
context = $(this).context;
//alert(context);
alert(context.nodeName);
if (context.nodeName != 'DIV'){
alert('not a div');
newContext = $(this).closest('div').context;
alert(newContext.nodeName);
}
});
};
})(jQuery);
</script>发布于 2011-07-20 23:00:53
Context是传递给JQuery()的DOM元素。因此,您的选择器首先将上下文和文档放在一起。
$('div.datemodule').limitDates(); // context is the document
$('.date_from').keydown(... // context is the document当涉及到回调时,如果你使用$(this),context就是触发事件的元素。
$('.date_from').keydown(function(){
$(this).limitDates(); // context is the element which has class .date_form and triggered that event
}); 当涉及到使用this.each的函数时,会在每次迭代中为每个元素设置上下文。
return this.each(function(){
$(this).context; // context is the element of iteration
}正如我所说的,上下文是传递给JQuery的内容,它可能是只读的。
发布于 2011-07-20 23:04:44
context的描述如下:
最初传递给jQuery()的DOM节点上下文;
因此,即使在调用closest之后,上下文仍然是传递给jQuery的原始input。
如果你想要div,为什么不直接买呢?
newContext = $(this).closest('div')[0];https://stackoverflow.com/questions/6763573
复制相似问题