我有一个以下结构的 div 列表,其中 a.status-progress
中的文本会说“正在进行”或“未开始”:
<div class="plan-section">
<div class="tableView-row">
<p class="plan-name">
<a>some name</a>
</p>
<a class="status-progress">in progress</a>
</div>
</div>
<!-- same structure as above but not expanded -->
<div class="plan-section"></div>
<div class="plan-section"></div>
所有<a>
每个标签带有 <div>
充当链接。我想做的是循环遍历每个 div,检查并查看 a.progress
是否其中有字符串“进行中”。如果没有,我想删除 cursor:pointer
css 属性和附加到 <a>
的任何事件标签。当前我的 jQuery 实现是:
// remove linking if plan is not joined
$('.status-progress').each(function(i){
var planLinks = $('.status-progress, .plan-name a');
var planStatus = $(this).text();
if (planStatus === "in progress"){
planLinks.css('cursor','pointer')
}
});
但这无法正常工作,因为我相信我的逻辑 each()
是错误的,或者我需要稍后在代码块中添加另一个。谢谢您的帮助!
编辑:为状态进度添加适当的类
最佳答案
行:
var planLinks = $('.status-progress, .plan-name a');
...将选择所有这样的 anchor 元素,而不仅仅是与.each()
循环的当前迭代相关的元素。获取相关内容的一种方法是:
var planLinks = $(this).closest("div").find("a");
即使用 DOM 遍历方法找到包含的 div,然后选择其中的 anchor 。或者您可以基于 sibling 等,但这更脆弱,因为对 html 结构的更改更有可能需要对 JS 进行更改。
但是,如果您执行以下操作,则实际上并不需要 .each()
循环:
$("a.status-progress:contains('in progress')") // find the 'in progress' anchors
.closest("div") // get their containing divs
.find("a") // find the anchors in those divs
.off() // remove the event handlers
.css('cursor','pointer'); // set the CSS property
关于javascript - 迭代元素列表并根据内部文本删除它们上的光标样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16919911/