jQuery Closest() 问题

标签 jquery closest

致所有人:抱歉,如果我不理解 StackOverflow 的协议(protocol)。我将立即努力纠正我在社区中的地位。话虽如此:

我试图根据调用它的内容来更改 jQuery 函数的上下文。在下面的代码中,当页面首次加载时,我们看到 limitDates() 函数被调用,并将 HTMLElementDiv 作为当前上下文。当我们通过在输入字段中键入来调用它时,我们看到它不是一个 div,但尝试使用 $(this).closest('div') 获取父 div 会返回一个 HTMLElementInput,而不是 div。有什么想法吗?

更新:已经创建了一个 fiddle :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>

最佳答案

Context 是传递给 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 的内容,并且可能是只读的。

关于jQuery Closest() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6763573/

相关文章:

javascript - 在 ajax 调用后再次运行 jquery 函数

jquery - 如何更改我的菜单以显示事件菜单

php - 选择距离按钮最近的文本区域

javascript - 更改最近的输入值?

javascript - jQuery:$(this) 与 this.$()

jquery - 使用 jquery 的类似 Twitter 的状态消息

javascript - noUiSlider - 限制值

c++ - 找到最接近另一个数字的数字c++

jQuery 查找最近的

javascript - .closest() 函数不适用于输入