当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


d3.js selection.filter()用法及代码示例


d3.js中的d3.selection.filter()函数用于过滤给定的选择并返回其过滤器为true的新选择。要使用的过滤器可以是字符串或函数。

用法:

selection.filter(filter);

参数:该函数接受上面提到并在下面描述的一个参数:

  • filter:它是一个字符串或一个函数,用于过滤选择。使用函数时,过滤器将应用于每个选定的元素。

返回值:此函数返回新选择。

范例1:本示例选择指定元素的所有奇数子代。



HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content= 
        "width=device-width,initial-scale=1.0"> 
      
    <script src= 
        "https://d3js.org/d3.v4.min.js"> 
    </script> 
    <script src= 
        "https://d3js.org/d3-selection.v1.min.js"> 
    </script> 
</head> 
  
<body> 
    <div> 
        <b>1. This text is in bold</b> 
        <b>2. This text is also in bold</b> 
        <b>3. Geeks for geeks</b> 
        <b>4. Geeks for geeks</b> 
        <b>5. Geeks for geeks</b> 
    </div> 
     
    <script> 
        let selection = d3.selectAll("b") 
            .filter(":nth-child(odd)") 
            .nodes(); 
        selection.forEach((e) => { 
            console.log(e.textContent) 
        }) 
    </script> 
</body> 
  
</html>

输出:

范例2:本示例选择指定元素的所有偶数子代。

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content= 
        "width=device-width,initial-scale=1.0"> 
    <script src= 
        "https://d3js.org/d3.v4.min.js"> 
    </script> 
    <script src= 
        "https://d3js.org/d3-selection.v1.min.js"> 
    </script> 
</head> 
  
<body> 
    <div> 
        <b>1. This text is in bold</b> 
        <b>2. This text is also in bold</b> 
        <b>3. Geeks</b> 
        <b>4. Geeks</b> 
        <b>5. Geeks for geeks</b> 
    </div> 
      
    <script> 
        let selection = d3.selectAll("b") 
            .filter(":nth-child(even)") 
            .nodes(); 
        selection.forEach((e) => { 
            console.log(e.textContent) 
        }) 
    </script> 
</body> 
  
</html>

输出:

范例3:本示例使用selection.selectAll作为过滤器。

HTML

<!DOCTYPE html> 
<html> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
  
    <script src= 
        "https://d3js.org/d3.v4.min.js"> 
    </script> 
    <script src= 
        "https://d3js.org/d3-selection.v1.min.js"> 
    </script> 
</head> 
  
<body> 
    <div> 
        <h3>1. This text is in bold</h3> 
        <h3>2. This text is also in bold</h3> 
        <h3>3. Geeks</h3> 
        <h3>4. Geeks</h3> 
        <h3>5. Geeks for geeks</h3> 
    </div> 
      
    <script> 
  
        // Using selection.selectAll with filter 
        let selection = d3.selectAll("div") 
            .selectAll("h3") 
            .filter(":nth-child(even)") 
            .nodes(); 
        selection.forEach((e) => { 
            console.log(e.textContent) 
        }) 
    </script> 
</body> 
  
</html>

输出:




相关用法


注:本文由纯净天空筛选整理自tarun007大神的英文原创作品 D3.js selection.filter() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。