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


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


D3.js中的d3.selection.on()函数用于将特定的事件侦听器添加到元素。事件可以是事件类型为click,mouseover等的字符串。

用法:

selection.on(typenames[, listener[, options]])

参数:此函数接受上述和以下描述的两个参数:

  • Typename Listener:这是一个字符串事件类型,例如单击,提交等。
  • Options:这是一个可选对象,可以说明侦听器的特殊特征。

注意:如果未指定侦听器,则它将返回特定元素的当前分配事件。

返回值:此函数返回对象。



以下示例说明了JavaScript中的D3.js selection.on()函数:

范例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.on() Function</title> 
    </head> 
    <style> 
        li { 
            background-color:green; 
            color:#ffffff; 
            width:50px; 
            margin-bottom:5px; 
            padding:20px; 
            height:40px; 
        } 
        li:hover { 
            cursor:pointer; 
            opacity:0.8; 
        } 
    </style> 
    <body> 
        <ul> 
            <li>Geeks for geeks</li> 
            <li>GEEKS FOR GEEKS</li> 
        </ul> 
        <script src= 
"https://d3js.org/d3.v4.min.js"> 
        </script> 
        <script src= 
"https://d3js.org/d3-selection.v1.min.js"> 
        </script> 
        <script> 
            let li = d3.select("li"); 
            let x = li.on("click", () => { 
                console.log("Clicked"); 
            }); 
        </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.on() Function</title> 
    </head> 
    <style> 
        li { 
            background-color:green; 
            color:#ffffff; 
            width:100px; 
            margin-bottom:5px; 
            padding:20px; 
            height:50px; 
        } 
        li:hover { 
            cursor:pointer; 
            opacity:0.8; 
        } 
    </style> 
    <body> 
        <ul> 
            <li>Geeks for geeks</li> 
        </ul> 
        <script src= 
"https://d3js.org/d3.v4.min.js"> 
        </script> 
        <script src= 
"https://d3js.org/d3-selection.v1.min.js"> 
        </script> 
        <script> 
            let li = d3.select("li"); 
            let x = li.on("mouseover", () => { 
                let li = document.querySelector("li"); 
                li.innerHTML = "mouseOver event"; 
            }); 
            // When cursor moves out of the li tag 
            x = li.on("mouseout", () => { 
                let li = document.querySelector("li"); 
                li.innerHTML = "Geeks for geeks"; 
            }); 
        </script> 
    </body> 
</html>

输出:

鼠标悬停时:

移出鼠标时:




相关用法


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