简体   繁体   中英

D3js, uncaught reference error when selecting rect in selectAll('rect')

I'm using D3 to make a chart. I want users to be able to enter their selections by resizing stacked bars on a single column horizontal column chart.

Bars are stacked and each have .call(drag) event listeners.

This drag event returns an error.

var drag = d3.behavior.drag()
    .on('drag', function() {

        var i = state.interactingWith //i represents current element
        var rects = d3.select('.svg').selectAll('.bar') //Get all stacked bars
        var handles = d3.select('.svg').selectAll('.handle') //Get all event handlers, on the edges of bars
        var currentX = d3.select(rects[0][i]).attr('x')

        d3.select(rects[0][i])
            .attr('width', d3.event.x - currentX)
        d3.select(handles[0][i])
            .attr('cx', d3.event.x)

        if (i < rects[0].length-1){

            var j = i+1 //I want to select the next element, but not if this element is the last
            var currentNextWidth = d3.select(rects[0][j]).attr('width') //This returns the error
            var newNextWidth = currentRightWidth + (+d3.event.x - currentX) 

            d3.select(rects[0][j])
                .attr('x', d3.event.x)                  
            d3.select(rects[0][j])
                .attr('width', newRightWidth)
            questions[i].displayWidth = newRightWidth   

        }
    })

Console says:

Uncaught TypeError: Cannot read property 'getAttribute' of null .... d3.min.js:3 

It says the offending line is var currentNextWidth ....

If I replace j with the desired index, it works as expected. Does anyone have any ideas as to what's going on here?

You have not mentioned how variable state and state.interactingWith is obtained. Try to put a debug point at offending line and log j, rect[0][j] in console to check these are available in current scope.

OK, so state.interactWith is a string.

I didn't realise i was a string, as it works fine by itself. i + 1 plays up though.

I think what's happened is i (string) works as array['1'] but i + 1 works as array['11'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM