簡體   English   中英

SVG矩形單擊事件監聽器

[英]SVG rectangle click eventlistener

我已經按照以下方式繪制了svg矩形,並嘗試通過以下方式向其添加click事件。但是,代碼無法正常工作。 我要去哪里錯了?

var enterElements = svgContainer.selectAll("rect") 
        .data(series).enter().append("rect")
        .attr("x", function(d, i){
             return xPosLoop[i];
            })
        .attr("height", function(d,i){
             return elementHeight[i];
            })
        .attr("y", function(d, i){
             return yPosLoop[i];
            })
        .attr("width", function(d,i){
             return elementWidth[i];
           })
        .attr("rx", 7)
        .attr("fill", function(d, i){
             return color[i];
            })
        .addEventListener('click', rect_click)
        .attr("stroke", "#006ec5")
        .attr("stroke-width", 1);
 function rect_click(event)
                    {
                        console.log('I was clicked');
                    } 

您正在使用d3選擇,而不是DOM元素本身。 要將事件偵聽器分配給選擇的元素,您可以執行以下操作:

.on('click', clickHandler)

將當前數據和元素索引傳遞給clickHandler 要訪問事件,請使用d3.event

function clickHandler(d, i) {
    // d is the datum
    // i is the index
    // this is the reference to the current element
    // d3.event is the reference to the current event
}

請參閱selection.on(type[, listener[, capture]])文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM