简体   繁体   English

JavaScript找不到脚本标签的ID

[英]Javascript can't find the script tag's id

I am facing problem with javascript document.getElementByID function. 我遇到了JavaScript document.getElementByID函数的问题。 The HTML file is: HTML文件是:

...
<script 
   id="scriptID"
   type="text/javascript"
   src="http://external.script.com/file.js">
</script>
...

When the page is loaded, the script is successfully included, but when executing expression from that file (the script is executed automaticaly after loading it): 加载页面时,脚本已成功包含在内,但是从该文件执行表达式时(脚本在加载后自动执行):

... = document.getElementById('scriptID').src

The script fails with message saying that "document.getElementById('scriptID') is null". 脚本失败,并显示消息“ document.getElementById('scriptID')为空”。 Can anybody tell me, why it is null if the tag is the script tag itself? 谁能告诉我,如果标签是脚本标签本身,为什么它为null?

Thx for any response. 谢谢任何回应。

EDIT: 编辑:
I don't know if that is relevant, but the page is built in a bit more complicated way. 我不知道这是否相关,但是页面的构建方式稍微复杂一些。 There is page of some product. 有一部分商品的页。 When the customer orders that product, there is a div loaded by AJAX with some "Thanks for order" and that contains the script. 当客户订购该产品时,AJAX会加载一个div,其中包含一些“感谢订单”,其中包含脚本。 Then the script is executed. 然后执行脚本。

May be your DOM is not ready when you are try to get src of script, 尝试获取脚本的src时,可能是您的DOM尚未准备好,

<script id="scriptID" type="text/javascript" src="http://external.script.com/file.js">
</script>

window.onload=function()
{
 alert( document.getElementById('scriptID').src);   
}

Its workinfg fine SEE 它workinfg精细SEE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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