当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - correct way to tell if my selection caught any existing elements

问题描述:

I'm making a toggle in d3, and trying to avoid global variables.

I can go ahead and select the item as though it was already in the scene:

d3.select('#awesome_line_graph')

and then test to see if I caught anything using

if (d3.select('#awesome_line_graph')[0].every(function(d){return d===null})){

// draw awesome line graph

} else {

d3.select('#awesome_line_graph').remove()

}

but this testing for the zeroth element for maybe more than one null thing seems terrible and hacky. How should I do it instead? Apologies for not knowing much javascript.

网友答案:

Use selection.empty. Also, if the selection is empty, there's no need to remove it.

网友答案:

I highly recommend you read Mike Bostock's D3 Workshop document. In it, he talks about how a selection returns an array of elements that match the selection criteria. Therefore, if the length of the array is greater than "0", you've properly matched and selected.

You may also want to read his documentation on "Nested Selections." I found it pretty useful.

I hope this helps.

Frank

分享给朋友:
您可能感兴趣的文章:
随机阅读: