jQuery 中最接近的函数并提取元素
Closest function in jQuery and extracting the elements
我有一个html片段如下:
<div id="samplediv">
<ul>
<li name="A">
<a id="A">
</li>
<li name="B">
<a id="B">
</li>
</ul>
</div>
我有一条短信叫:
var text = "B";
我想检查文本是否与 li 的任何元素匹配,并为锚元素添加一个 class 名称 "disable" 不与文字相匹配。
我的情况是我想为
添加一个名为 "disable" 的 class
<a id="A">
这是我试过的:
$("#samplediv li").each(function() {
if($(this).name != text){
$(this).closest("a").addClass("disabled");
}
});
但这里的事情是 $(this).name
正在评估 "undefined"
。我缺少什么?
编辑:由于打字错误,错过了标签
有多个问题,
$(this)
returns 没有 name
属性 的 jQuery 对象,您可以使用 $(this).attr('name')
.closest()
用于查找祖先元素,但是a
是li
元素的后代,所以需要使用find()
您可以找到所有没有给定名称的 li
元素,然后在其中找到 a
元素,如
var text = 'B';
$("#samplediv li").not('[name="' + text + '"]').find("a").addClass("disabled");
a.disabled {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
<ul>
<li name="A">
<a id="A">a</a>
</li>
<li name="B">
<a id="B">b</a>
</li>
</ul>
</div>
var text = "B";
$("#samplediv li").filter(function() {//use filter
return $(this).attr('name') != text;//use .attr() to get name attribute
}).find('a').addClass("disabled");//use find to get the anchor tag
.disabled{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
<ul>
<li name="A">
<a id="A">a</a>
</li>
<li name="B">
<a id="B">b</a>
</li>
</ul>
</div>
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.
我有一个html片段如下:
<div id="samplediv">
<ul>
<li name="A">
<a id="A">
</li>
<li name="B">
<a id="B">
</li>
</ul>
</div>
我有一条短信叫:
var text = "B";
我想检查文本是否与 li 的任何元素匹配,并为锚元素添加一个 class 名称 "disable" 不与文字相匹配。 我的情况是我想为
添加一个名为 "disable" 的 class<a id="A">
这是我试过的:
$("#samplediv li").each(function() {
if($(this).name != text){
$(this).closest("a").addClass("disabled");
}
});
但这里的事情是 $(this).name
正在评估 "undefined"
。我缺少什么?
编辑:由于打字错误,错过了标签
有多个问题,
$(this)
returns 没有name
属性 的 jQuery 对象,您可以使用$(this).attr('name')
.closest()
用于查找祖先元素,但是a
是li
元素的后代,所以需要使用find()
您可以找到所有没有给定名称的 li
元素,然后在其中找到 a
元素,如
var text = 'B';
$("#samplediv li").not('[name="' + text + '"]').find("a").addClass("disabled");
a.disabled {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
<ul>
<li name="A">
<a id="A">a</a>
</li>
<li name="B">
<a id="B">b</a>
</li>
</ul>
</div>
var text = "B";
$("#samplediv li").filter(function() {//use filter
return $(this).attr('name') != text;//use .attr() to get name attribute
}).find('a').addClass("disabled");//use find to get the anchor tag
.disabled{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
<ul>
<li name="A">
<a id="A">a</a>
</li>
<li name="B">
<a id="B">b</a>
</li>
</ul>
</div>
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.