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

查看:15
本文介绍了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天全站免登陆