遍历元素列表并根据内部文本删除元素上的游标样式

Iterating through a list of elements and removing the cursor style on them based on inner text

本文关键字:元素 删除 游标 样式 文本 内部 列表 遍历      更新时间:2023-09-26

我在以下结构中有一个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>

每个<div>中的所有<a>标签作为链接。我想做的是循环遍历每个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()逻辑是错误的,或者我需要在代码块中添加另一个。谢谢你的帮助!

编辑:为status-progress添加适当的类

一行:

var planLinks = $('.status-progress, .plan-name a');

…将选择所有这样的锚元素,而不仅仅是与.each()循环的当前迭代相关的锚元素。获取相关内容的一种方法是:

var planLinks = $(this).closest("div").find("a");

也就是说,使用DOM遍历方法查找包含它的div,然后选择其中的锚。或者你可以基于兄弟姐妹等等,但这更脆弱,因为对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