简体   繁体   English

如何在Javascript脚本的src标记中使用函数

[英]How to use a function in the src tag of an Javascript script

I have some HTML code and there somewhere I want to display a video with Javascript. 我有一些HTML代码,并且我想在某处显示带有Javascript的视频。 I have a function that gives me a valid link to the video player and source. 我有一个功能,可以为我提供到视频播放器和源的有效链接。 So if I post it directly without function in src it works fine. 因此,如果我直接在src发布时不带功能,则效果很好。

So my question is how can I use my function in the src tag? 所以我的问题是如何在src标签中使用我的函数?

<script type="text/javascript" src="get_link()"</script>

A solution without jQuery/document.* is wanted if possible. 如果可能,需要一个没有jQuery / document。*的解决方案。 I know I could do something like that document.getElementById("iframeid").setAttribute("src","link") . 我知道我可以做类似document.getElementById("iframeid").setAttribute("src","link")事情。

Edit 编辑

All of the solutions were not working in my case. 在我的情况下,所有解决方案均无效 But anyways it's not a solution for me to do it in Javascript because of security issues. 但是无论如何,由于安全问题,这不是我用Javascript来解决的解决方案。 And there is no way to use nodejs. 而且没有办法使用nodejs。 So thanks for your comments anyway. 所以还是谢谢您的评论。 =) =)

Try adding script in JavaScript like this: 尝试像这样在JavaScript中添加脚本:

var script = document.createElement('script');
script.setAttribute('src', get_link());
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);

If you want to set this attribute through JavaScript, you can't do so by directly putting it in the src attribute. 如果要通过JavaScript设置此属性,则不能通过直接将其放在src属性中来进行设置。 You can attach some event handler on the HTML, such as onclick="handler()" , or something of that sort, which when triggered will give you access to the element within the function. 您可以在HTML上附加一些事件处理程序,例如onclick="handler()"或类似的事件处理程序,当触发该事件处理程序时,您将可以访问函数中的元素。 Something like this. 这样的事情。

function handler() {
    this.src= 'my_link.js
}

EDIT: 编辑:

Not that the above solution is ideal, but just to meet the criteria of the question. 并非以上解决方案是理想的,而仅仅是为了满足问题的标准。 It is possible, without any use of document to do this. 可以不使用任何文档来执行此操作。

On your script tag, set an onerror="change_link()" . 在脚本标签上,设置onerror="change_link()" Then define an 然后定义一个

function change_link() {
    this.src= get_link();
}

And last, you should add a faulty src attribute to the script tag. 最后,您应该在脚本标记中添加错误的src属性。 Again, this is stupid and you shouldn't do it in production code, but I'm just showing you that it's possible. 同样,这很愚蠢,您不应该在生产代码中这样做,但我只是向您展示这是可能的。

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

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