简体   繁体   English

禁用 html 文件中的脚本标签或使用 javascript 更改脚本标签类型/src

[英]Disable script tag in html file or change script tag type/src using javascript

I want to disable the script tag or if its possible to change script src or type in this script using javascript?我想禁用脚本标签,或者是否可以使用 javascript 更改脚本srctype此脚本?

<script type="text/javascript" src="./1.js.download"></script>

I can't add id in this code.我无法在此代码中添加id

please help and feel free to ask anything if you don't understand如果您不明白,请帮助并随时提出任何问题

How about removing it altogether?完全删除它怎么样? The example is a simple function that get an element by the given selector and remove it.该示例是一个简单的 function,它通过给定的selector获取一个元素并将其删除。 FYI if you don't want the <script> to actually load, then your'e out of luck.仅供参考,如果您不希望<script>实际加载,那么您就不走运了。 It'll be parsed as long as it's in the HTML, there's no way to avoid it from loading by JavaScript.只要它在 HTML 中就会被解析,没有办法避免它被 JavaScript 加载。

In the example there are 3 <script> tags and the target is in the middle.在示例中,有 3 个<script>标签,目标位于中间。 document.querySelector("script") will stop at the first match so you'll need a more specific selector. document.querySelector("script")将在第一个匹配项处停止,因此您需要一个更具体的选择器。 To target the second tag I used script:nth-of-type(2) .为了定位第二个标签,我使用了script:nth-of-type(2) You can verify success using by F12您可以使用F12验证成功

 const killTag = selector => document.querySelector(selector).remove(); killTag(`script:nth-of-type(2)`);
 <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="./1.js.download"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

You can remove src from script tag like this:您可以像这样从脚本标签中删除 src:

 s = document.querySelectorAll('script') console.log(s[1]) s[1].setAttribute('src', '') console.log(s[1])
 <script type="text/javascript" src="./1.js.download"></script>

You will have maybe multiple scripts in your dom.您的 dom 中可能会有多个脚本。 then you have take a look which element it is and change the key from the collection.然后你看看它是哪个元素并从集合中更改键。 in this case the key was 1.在这种情况下,密钥是 1。

If you need to select specific script element you can get it by attribute like this:如果您需要 select 特定script元素,您可以通过如下属性获取它:

 let ok = document.querySelector('[src="./1.js.download"]'); //Then you can either change id or type: ok.setAttribute('id', 'ok'); ok.setAttribute('type', 'module');

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

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