问题:给定一个特定的容器dom元素(窗口,div,字段集等),在该DOM元素中查找类(.FormWidget)的所有元素,以递归方式搜索所有容器的后代.包含但不要查看具有匹配类(.FormWidget)的元素.元素可以嵌套到n个级别.
例如,给定此HTML:
<fieldset id="MyFieldset" class="FormWidget FieldSetMultiplier">
<legend>My Legend</legend>
<div>
<label for="Field1">Field1</label>
<input type="text" name="Field1" value="" id="Field1" class="BasicInput FormWidget">
</div>
<div id="SomeWidget" class="FormWidget">
<label for="Field2">Field2</label>
<div name="Field2" id="Field2" class="FormWidget RestrictedComboBox"></div>
<input type="text">
</div>
</fieldset>
<div>
<label for="Field3">Field3</label>
<input type="text" name="Field3" value="" id="Field3" class="BasicInput FormWidget">
</div>
Run Code Online (Sandbox Code Playgroud)
例1:
让伪Jquery函数".findButNotInside()"代表我正在寻找的功能.
$(document).findButNotInside('.FormWidget');
Run Code Online (Sandbox Code Playgroud)
应该只返回#MyFieldset和#Field3.从窗口开始,字段1和2以及#SomeWidget是FormWidgets,但是不能包含它们,因为不允许该函数查看其他.FormWidgets以查找FormWidgets..FormWidget字段集中的任何内容都是禁止的.
例2:
$('#MyFieldset').findButNotInside('.FormWidget');
Run Code Online (Sandbox Code Playgroud)
应该只返回#Field1和#SomeWidget.它应该.FormWidget在目标#MyFieldset字段集中查找s ,但不应返回#Field2,因为不允许查看.FormWidget(在本例中为#SomeWidget)内部以查找其他.FormWidgets.
我认为这可以用正确的函数和选择器完成,但我不确定应该如何构造选择器?
$.fn.findButNotInside = function(selector) {
var origElement = $(this);
return origElement.find(selector).filter(function() {
var nearestMatch = $(this).parent().closest(selector);
return nearestMatch.length == 0 || origElement.find(nearestMatch).length == 0;
});
};
Run Code Online (Sandbox Code Playgroud)
小提琴.诀窍是检查它nearestMatch实际上是否在我们的搜索上下文中.
并注意这个无效:
$('window').findButNotInside('.FormWidget');
Run Code Online (Sandbox Code Playgroud)
...因为没有<window>标签.你想要的是:
$(document).findButNotInside('.FormWidget');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1152 次 |
| 最近记录: |