jquery中find和nearest之间的区别 [英] Difference between find and closest in jquery
问题描述
我试图理解jquery中find()和nearest()之间的区别。以下是我使用jquery的简单代码。 *这只是一个虚拟表格。我只是想了解它们之间的区别。所以不要以为我要用这个简单的形式做什么。 *
I am trying to understand the difference between find() and closest() in jquery. Following is my simple code with jquery. *This is just a dummy form. I just want to understand the difference between them. So don't think what am I going to do with this simple form. *
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function myFunction(){
var form = $("div#d1").find("form").attr("action");
var form1 = $("div#d1").closest("form").attr("action");
alert(form+form1);
}
</script>
</head>
<body>
<div id="d1">
<p id="p1">Click on this paragraph.</p>
<p id="p2">Click on this paragraph.</p>
<form id="f1" action="aaa">
<input type="text" value="submit">
</form>
<form id="f2" action="bbbbb">
<input type="text" value="submit">
</form>
<form id="f3" action="ccb">
<input type="text" value="submit">
</form>
<input type="submit" value="submit" onclick="myFunction()">
</div>
</body>
</html>
当我点击我的提交按钮时, var form1
值显示为未定义。任何人都可以告诉我为什么它显示为未定义?当我应该使用nearest()和find()。
When I click on my submit button, var form1
value is showing as undefined. Can anyone tell me why it is showing as undefined? Also when I should use closest() and find().
推荐答案
nearest()
是上树,进入父母,包括当前元素。 find()
正在向下查看孩子的树,以及孩子的孩子:
closest()
is to go up the tree, into the parents, including the current element. find()
is going down the tree looking in the childs, and the childs of childs:
var form1 = $("input").closest("form").attr("action");
这篇关于jquery中find和nearest之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!