Javascript从层次结构的html获取文本

时间:2017-08-25 07:59:35

标签: javascript html

这是我的代码:

var label;
$('.card-label.mod-card-detail ').each((index, element) => {
    text = $(element).text().toUpperCase();
    switch(text){
        case "CODE REVIEW": 
            label = text;
            break;
        case "HOTFIX":
            if(label !== "CODE REVIEW") label = text;
            break;
        case "BUG":
            if(label !== "CODE REVIEW" && label !== "HOTFIX") label = text;
            break;
        case "FEATURE":
            if(label !== "CODE REVIEW" && label !== "HOTFIX" && label !== "BUG") label = text;
    }
})

我从html文件中获取标签名称。我需要应用标签层次结构:CODE REVIEW -> HOTFIX -> BUG -> FEATURE。有没有办法让这个代码更清洁,更有效?

2 个答案:

答案 0 :(得分:0)

一种方法:

  1. 使用标签键创建一个对象并指定相应的权重。

  2. 将此对象推入数组

  3. 使用自定义排序
  4. 
    
    //Label texts : CODE REVIEW -> HOTFIX -> BUG -> FEATURE
    //Corresponding weights : 4 -> 3 -> 2 -> 1
    
    
    // decalre array 
    var labelArr = [];
    //push objects in switch case to this array
    var labelText = {  
        text: 'CODE REVIEW' ,  
        weight: 4
    };
    var labelText1 = {  
        text: 'HOTFIX' ,  
        weight: 3
    };
    var labelText2 = {  
        text: 'BUG' ,  
        weight: 2
    };
    labelArr.push(labelText);
    labelArr.push(labelText1);
    labelArr.push(labelText2);
    
    
    
    labelArr.sort(
              function(x, y)
              {
                 return y.weight - x.weight ;
              }
            );
    // Teatr White White 023 White flower
    console.log(labelArr);
    var finalLabel = labelArr.map(function(a) {return a.text;});
    document.write(finalLabel.join('->'));
    
    
    

答案 1 :(得分:0)

我认为我有一个更简单的解决方案,只使用一个元素,不需要sort()或map():

var labels = ['FEATURE', 'BUG', 'HOTFIX', 'CODE REVIEW'],
    priority = -1;

$('.card-label.mod-card-detail ').each((index, element) => {
    let text = $(element).text().toUpperCase(),
        current_priority = labels.indexOf(text);

    // we found something with higher priority
    if(current_priority > priority) {
        priority = current_priority;
    }
});

if(priority < 0) {
    console.log("No labels found");
} else {
    let resulting_text = labels[priority];
    console.log("Highest priority found:", resulting_text);
}