没有 jQuery 的目标 href 地址的特定部分
Target particular section of href address without jQuery
首先,
有没有办法将 href
link 的特定部分用于 if
语句?
基本上我如何定位以下 href
link:
的 C 部分
href="/a/b/c/d/e/index.html";
其次,
JavaScript 中所需的 if
语句,最好用文字描述,是:
"If section three contains C, do something."
最后,
我想使用每个 div
的 href
为下面显示的 HTML
应用 if
语句,以便添加到 classList
样本:
<div class="a-1" href="/a/b/c/d/e/index.html">
<a class="location">text</div>
</div>
你可以尝试用split()
生成一个数组来匹配特定位置的字符:
var href="/a/b/c/d/e/index.html";
href = href.split('/');
if(href.indexOf('c') == 3){
console.log('Matched at position:', href.indexOf('c'));
}
但是,如果您希望根据来自多个元素的不同 href
实现 if
语句,则需要创建一个实现 forEach
的 Array
,以及 select 您希望实现哪些元素 classList.add()
,如下所示:
var divs = Array.from(document.querySelectorAll("div"));
divs.forEach(function(div) {
var href = document.querySelector(".a-1").getAttribute("href");
var location = div.querySelector(".location");
href = href.split("/");
if (href.indexOf("c") == 3) {
location.classList.add("c");
}
})
首先,
有没有办法将 href
link 的特定部分用于 if
语句?
基本上我如何定位以下 href
link:
href="/a/b/c/d/e/index.html";
其次,
JavaScript 中所需的 if
语句,最好用文字描述,是:
"If section three contains C, do something."
最后,
我想使用每个 div
的 href
为下面显示的 HTML
应用 if
语句,以便添加到 classList
样本:
<div class="a-1" href="/a/b/c/d/e/index.html">
<a class="location">text</div>
</div>
你可以尝试用split()
生成一个数组来匹配特定位置的字符:
var href="/a/b/c/d/e/index.html";
href = href.split('/');
if(href.indexOf('c') == 3){
console.log('Matched at position:', href.indexOf('c'));
}
但是,如果您希望根据来自多个元素的不同 href
实现 if
语句,则需要创建一个实现 forEach
的 Array
,以及 select 您希望实现哪些元素 classList.add()
,如下所示:
var divs = Array.from(document.querySelectorAll("div"));
divs.forEach(function(div) {
var href = document.querySelector(".a-1").getAttribute("href");
var location = div.querySelector(".location");
href = href.split("/");
if (href.indexOf("c") == 3) {
location.classList.add("c");
}
})