简体   繁体   English

将源分配给html元素

[英]assigning source to html element

I have a question about the code below. 我对以下代码有疑问。 This is a code snippet I copied from an example. 这是我从一个示例中复制的代码片段。 I don't understand why it works because I don't know why it can assign a URL to myscript.src. 我不明白为什么会这样,因为我不知道为什么它可以为myscript.src分配一个URL。 I searched for properties with element here and it doesn't have a property called src. 在这里搜索带有element的属性,它没有名为src的属性。 Can someone offer any explanation? 有人可以提供任何解释吗? Thank you! 谢谢!

if (document.createElement && document.body) 
{ 
    var myscript = document.createElement('SCRIPT'); 
    myscript.src = document.location.protocol + '//myURLhere'; 
    document.body.appendChild(myscript); 
}

src is not an attribute of every element type, which is why you don't see it in that specific MDC page. src并不是每个元素类型的属性,这就是为什么您在该特定MDC页面中看不到它的原因。 It is, however, an attribute of script elements. 但是,它是script元素的属性。

You can also reference the HTML(5) spec directly for this sort of thing. 您也可以直接为此类事情引用HTML(5)规范

When linking to an external script, you would use the src attribute. 链接到外部脚本时,将使用src属性。

Example: <script src="myscripts.js"></script> 示例: <script src="myscripts.js"></script>

Edit: 编辑:

No, that will not work, because <div> does not have a src attribute. 不,这将不起作用,因为<div>没有src属性。 In order to load external data into a div, you would need to use AJAX. 为了将外部数据加载到div中,您将需要使用AJAX。 Once you load your external data from ajax, then you would use div.innerHTML = ajaxresponse; 从ajax加载外部数据后,您将使用div.innerHTML = ajaxresponse;

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

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