2

致所有人:抱歉,如果我不了解 StackOverflow 的协议。我将立即努力纠正我在社区中的地位。话说回来:

我正在尝试根据调用它的内容来更改 jQuery 函数的上下文。在下面的代码中,当页面第一次加载时,我们看到 limitDates() 函数以 HTMLElementDiv 作为当前上下文被调用。当我们通过在输入字段中键入来调用它时,我们看到它不是一个 div,但是尝试使用 $(this).closest('div') 获取父 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>
4

2 回答 2

2

上下文是传递给 JQuery() 的 DOM 元素。因此,您的选择器首先将上下文作为文档。

$('div.datemodule').limitDates(); // context is the document
$('.date_from').keydown(...   // context is the document

当涉及到回调时,如果使用 $(this) 上下文是触发事件的元素。

$('.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-20T15:00:52.980 回答
1

上下文的描述是:

The DOM node context originally passed to jQuery();

所以即使在调用closest上下文之后仍然是原来的input传递给jQuery.

如果你想得到div,为什么不直接得到呢?

newContext = $(this).closest('div')[0];
于 2011-07-20T15:04:44.190 回答