我的DOM中有多个链接元素,希望通过href
属性搜索特定的链接元素。
有效的代码: (过滤匹配的href后删除第二个链接)
$(document).ready(() => {
const ele = getLinkElementByUrl("/link2");
$(ele).remove();
});
const getLinkElementByUrl = (url) => {
const links = $(".l"); // find all links
var element = null;
for (let i = 0; i < links.length; i++) {
let ele = links[i];
let href = $(ele).attr('href');
if (href == url) { // matching href?
element = ele;
break;
}
}
return element;
}
&#13;
a {
text-decoration: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="l" href="/link1">Link 1</a>
<br>
<a class="l" href="/link2">Link 2</a>
<br>
<a class="l" href="/link3">Link 3</a>
&#13;
我希望代码缩短。我试过这段代码
$(document).ready(() => {
const ele = getLinkElementByUrl("/link2");
$(ele).remove();
});
const getLinkElementByUrl = (url) => {
return $(".l").find(current => $(current.attr('href')) == url);
}
&#13;
a {
text-decoration: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="l" href="/link1">Link 1</a>
<br>
<a class="l" href="/link2">Link 2</a>
<br>
<a class="l" href="/link3">Link 3</a>
&#13;
搜索函数返回一个空数组而不是匹配的链接元素。
我的语法错了吗?
答案 0 :(得分:1)
你可以试试这个:
$(document).ready(() => {
const ele = getLinkElementByUrl("/link2");
$(ele).remove();
});
const getLinkElementByUrl = (url) => {
return $(".l[href='"+ url + "']:eq(0)");
}
a {
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="l" href="/link1">Link 1</a>
<br>
<a class="l" href="/link2">Link 2</a>
<br>
<a class="l" href="/link3">Link 3</a>
答案 1 :(得分:1)
要获得预期结果,请使用 jQuery [attribute $ = value]选择器
查找元素的以下选项const getLinkElementByUrl = (url) => {
return $("a[href$='/link2']")
}
代码示例 - https://codepen.io/nagasai/pen/LdrjVJ
$(document).ready(() => {
const ele = getLinkElementByUrl("/link2");
//console.log("ele",ele);
$(ele).remove();
});
const getLinkElementByUrl = (url) => {
return $("a[href$='/link2']")
}
&#13;
a {
text-decoration: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="l" href="/link1">Link 1</a>
<br>
<a class="l" href="/link2">Link 2</a>
<br>
<a class="l" href="/link3">Link 3</a>
&#13;