JQuery 2.0最接近上下文

时间:2014-01-14 17:02:06

标签: javascript jquery

我认为将DOM元素作为上下文添加到JQuery方法会限制该方法仅查看该元素及其后代而不是整个文档。如果是这种情况......

为什么这样:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script src="jquery-2.0.2.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="styles.css"/>
    <script type="text/javascript">
        $(document).ready(function() {

            var contextElem = document.getElementById("row1");
            $("img").closest(".drow", contextElem).each(function(index, elem) {
                console.log("Context Element: " + elem.tagName + " " + elem.className
                            + " " + elem.id);
            });    

        });     
    </script>
</head>
<body>
    <h1>JQuery Closest Example</h1>
    <form method="post">
        <div id="oblock">        
            <div class="dtable">
                <div id="row1" class="drow">
                    <div class="dcell">
                        <img src="cell11.png"/><label for="cell11">Cell 1 1:</label>
                        <input name="cell11Value" value="0" required>
                    </div>
                    <div class="dcell">
                        <img src="cell12.png"/><label for="cell12">Cell 1 2:</label>
                        <input name="cell12Value" value="0" required >
                    </div>               
                </div>
                <div id="row2"class="drow">
                    <div class="dcell">
                        <img src="cell21.png"/><label for="cell21">Cell 2 1:</label>
                        <input name="cell21Value" value="0" required>
                    </div>
                    <div class="dcell">
                        <img src="cell22.png"/><label for="cell22">Cell 2 2:</label>
                        <input name="cell22Value" value="0" required >
                    </div>       
                </div>            
            </div>
        </div>
        <div id="buttonDiv"><button type="submit">Save</button></div>                    
    </form>
</body>
</html>
J

在控制台中生成此内容:

Context Element:DIV drow row2

而不是:

Context Element:DIV drow row1

???

1 个答案:

答案 0 :(得分:1)

传递上下文意味着jQuery将查找您的选择器作为context的后代。在您的情况下,您的选择器和context是相同的元素。