如何检查一个类是否存在于链接中
how to check if a class exist in a link?
我试图检查一个条件,如果一个链接包含" current
"类,那么我需要执行一些操作。链接有一个自定义属性" data-step"
.
当data-step="3"
将包含一个类电流时,我需要执行一些操作。
链接在这里:
<a href="#" data-step="1" class="multistep_section">login</a>
<a href="#" data-step="2" class="multistep_section">billing address</a>
<a href="#" data-step="3" class="current multistep_section">Shipping Address</a>
<a href="#" data-step="4" class="multistep_section">payment</a>
<a href="#" data-step="5" class="multistep_section">order review</a>
类电流是可变的,并根据步骤变化。只有当data-step="3"
包含类"当前"
欢迎提出任何建议
根据海报反馈编辑回复:
$(document).ready(function(){
if ($('a[data-step=3]').hasClass('current')){
// Current class exists on data-step 3
}
});
和纯JS:
(function(){
var elements = document.querySelectorAll('[data-step]');
var targetElement;
for (var i = 0; i < elements.length; i++){
if (elements[i].getAttribute('data-step') == 3){
targetElement = elements[i];
}
}
if (targetElement.classList.contains('current')){
alert("Has current class");
}
})();
参见纯JS示例:http://jsfiddle.net/19tmab49/4/
document.addEventListener("DOMContentLoaded", function(event) {
var links = document.getElementsByTagName("a");
var class_name = "current";
// if element is contained in an array (function)
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
for(var i = 0; i < links.length; i++) {
var tempLink = links[i]; // represents each links
var dataStep_value = tempLink.getAttribute("data-step"); // getting "data-step" value
var classes = tempLink.className.split(" ");
if (isInArray(class_name, classes)) {
// current is in array, do whatever you need to
}
}
});
<a href="#" data-step="1" class="multistep_section">login</a>
<a href="#" data-step="2" class="multistep_section">billing address</a>
<a href="#" data-step="3" class="current multistep_section">Shipping Address</a>
<a href="#" data-step="4" class="multistep_section">payment</a>
<a href="#" data-step="5" class="multistep_section">order review</a>
您将不会看到这个函数的结果,而是在我注释的区域添加一个警告。这个脚本检查data-step
属性,如果它们包含类"current"(变量class_name
),则检查另一个设置为"3"的时间。
相关文章:
- Facebook共享链接适用于用户,但不适用于粉丝页面管理员
- 链接适用于所有浏览器,除了 safari(php 代码)
- “add”函数适用于不同的链接/参数组合
- 将函数应用于页面上的所有链接
- Javascript then() 链接 - Deferred 第二个 then() 对应于哪个
- 我如何完善这个Javascript代码,使其只适用于来自图像的链接(而不是来自文本的链接)
- 如果存在跨度,则将类添加到链接
- 我可以让浏览器专注于这些链接吗?
- 链接是否可以调用它指向的页面上存在的 javascript
- 如何获取使用java脚本的网页中存在的所有链接
- 通过单击删除同一行中存在的链接来删除特定行
- 在添加之前检查是否存在 css 引用链接
- HTML 页面转到内联链接(当存在固定导航栏时)
- 获取链接 href 并将其应用于另一个链接 jQuery
- D3:方向图类似于树形布局,但带有反向链接
- 平滑滚动仅适用于同一页面,而不适用于外部链接
- 将字符串中的 url 替换为 href 链接 - 适用于多种地址类型
- jQueryMobile中的程序化(相对于基于链接的)导航
- 如何检查一个类是否存在于链接中
- 如果至少有一个输入不是原始的,我如何将CSS应用于链接,如果所有输入都是原始的,我如何撤销该更改?