d3.select(“#element")在html元素上方的代码不起作用时 [英] d3.select("#element") not working when code above the html element

查看:114
本文介绍了d3.select(“#element")在html元素上方的代码不起作用时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效:

<div id="chart"></div>
<script>var svg = d3.select("#chart").append("svg:svg");</script>

这不是:

<script>var svg = d3.select("#chart").append("svg:svg");</script>
<div id="chart"></div>

我尝试将代码包装在jquery document.ready()中,使用jquery捕获元素,然后将其传递到d3.select中,但这也不起作用. 编辑一旦我正确使用了jquery document.ready()语法,它就可以工作.

I tried wrapping the code in a jquery document.ready(), grabbing the element with jquery, and passing it into d3.select, but that didn't work either. Edit Once I got the jquery document.ready() syntax right, it worked.

通过任何方式,我都可以在页面顶部包含javascript并仍然在下面选择一个元素?谢谢.

Any way I can include the javascript at the top of the page and still select an element below? Thanks.

推荐答案

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

换句话说,这不会发生,因为您无法查询尚不存在的内容-因此只需在页面加载后执行此操作(此处通过jquery)即可.

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

顺便说一句,它建议您将JS文件放置在body标签关闭之前.

Btw, its recommended that you place your JS files before the close of your body tag.

这篇关于d3.select(“#element")在html元素上方的代码不起作用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆