當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


d3.js selection.attr()用法及代碼示例

selection.attr()函數用於設置所選元素的屬性。使用此函數可以設置屬性名稱和屬性值。

用法:

selection.attr(name[, value]);

參數:該函數采用兩個參數,如上所示和下麵所述:

  • name:它是屬性的名稱。
  • value:它是屬性的值。

返回值:此函數不返回任何值。

範例1:



HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" path1tent= 
        "width=device-width,initial-scale=1.0"> 
          
    <title>D3.js selection.attr() Function</title> 
  
    <script src= 
        "https://d3js.org/d3.v4.min.js"> 
    </script> 
  
    <style> 
        p { 
            line-height:5px; 
        } 
    </style> 
</head> 
  
<body> 
    <div> 
        <p>GeeksforGeeks</p> 
    </div> 
  
    <script> 
        var div = d3.select("p") 
            .attr("name", "This is from name attribute"); 
        var divselect = document.querySelector("p"); 
        console.log(divselect.getAttribute("name")); 
    </script> 
</body> 
  
</html>

輸出:

範例2:

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" path1tent= 
        "width=device-width,initial-scale=1.0"> 
  
    <title>D3.js selection.attr() Function</title> 
  
    <script src= 
        "https://d3js.org/d3.v4.min.js"> 
    </script> 
  
    <style> 
        p { 
            line-height:5px; 
        } 
    </style> 
</head> 
  
<body> 
    <div> 
        <a>GeeksforGeeks</a> 
    </div> 
      
    <script> 
        var a = d3.select("a").attr("href",  
            "https://www.geeksforgeeks.org"); 
  
        var divselect = document.querySelector("a"); 
          
        console.log("This is from a attr href:",  
                divselect.getAttribute("href")); 
    </script> 
</body> 
  
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js selection.attr() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。