使用HTML脚本标记在源代码中进行编码 [英] Using HTML script tags to code while they have a source

查看:87
本文介绍了使用HTML脚本标记在源代码中进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到< script src =...>< / script> 标签不允许您在其中使用JavaScript,例如:

 < script src =myFile.js> 
alert(这是一个测试);
< / script>

这不起作用,也不会在FireBug中引发错误,为什么会发生这种情况,我们是否需要添加额外的< script> 标签以允许JS在表单本身上使用?





我有一个文件,找到@ script / addScript.js 我的根,这包含:

$ p $ function addScript($ src)
{
var script = document .createElement('script');
script.type =text / javascript;
script.src = $ src;
document.getElementsByTagName('head')[0] .appendChild(script);
}

这是为了让我能够快速有效地向DOM添加脚本,所以我试图做到这一点:

 < script src =script / addScript.js> 
addScript(script / obj.js);
addScript(script / home / login.js);
< / script>

但它不起作用,所以我必须这样做:

 < script> 
addScript(script / obj.js);
addScript(script / home / login.js);
< / script>


解决方案

脚本元素加载单个脚本。



可以通过URL或内联方式执行此操作,但它仍会加载脚本,因此无法同时执行这两个操作。



如果您尝试执行这两个操作,内联脚本将被忽略:

 < script src =example.js> 
this_is_ignored();
< / script>

...所以您需要多个脚本元素。

 < script src =example.js> 
< / script>
< script>
this_is_NOT_ignored();
< / script>






值得注意的是脚本的内容元素仍然存在于DOM中,因此有些人使用它来存储由src引用的JS读取的数据。 data - * 属性(可以说)是一种更干净的方法。


I noticed that the <script src="..."></script> tag does not allow you to use JavaScript within it, such as:

<script src="myFile.js">
    alert( "This is a test" );
</script>

And this does not work, nor does it throw an error in FireBug, why is this happening, why do we have to add extra <script> tags to allow for JS to be used on the form itself?

Example

I have a file, found @ script/addScript.js from my root, and this contains:

function addScript( $src )
{
    var script = document.createElement( 'script' );
    script.type = "text/javascript";
    script.src = $src;
    document.getElementsByTagName( 'head' )[0].appendChild( script );
}

This is designed to allow me to add scripts to the DOM quickly and effectively, so I tried to do this:

<script src="script/addScript.js">
    addScript( "script/obj.js" );
    addScript( "script/home/login.js" );
</script>

But it did not work, so I have to do this instead:

<script>
    addScript( "script/obj.js" );
    addScript( "script/home/login.js" );
</script>

解决方案

A script element loads a single script.

It can do that from either a URL or from inline, but it still loads a script so it can't do both.

If you try to do both, the inline script will be ignored:

<script src="example.js">
    this_is_ignored();
</script>

… so you need multiple script elements.

<script src="example.js">
</script>
<script>
    this_is_NOT_ignored();
</script>


It is worth noting that the content of the script element will still exist in the DOM, so some people use it to store data in it which the JS referenced by the src will read. data-* attributes are (arguably) a cleaner approach to that though.

这篇关于使用HTML脚本标记在源代码中进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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