问题描述
我在JavaScript逻辑中执行了大量的HTML代码,我想知道是否有人可以指出我做错了什么?我想要实现的是基于概率运行视频。这是我的代码:
I am having a hard executing a chunk of HTML code inside my JavaScript logic, i was wondering if someone could point out what i am doing wrong? What i am trying to achieve is run either video based on probability. Here is my code:
<html>
<head>.</head>
<body>
<script>
function myFunction() {
var chance = (( Math.random()*100)+1)
if (chance>= 0 || chance<=50){
<video controls autoplay name="media">
<source src="http://webmup.com/195a3/vid.webm" type="video/webm">
</video>
}
else {
<video controls autoplay name="media">
<iframe width="420" height="315"
<source src="https://www.youtube.com/embed/IdtKbq3Omkw" type="video/webm">
</ifrmae>
</video>
}
}
</script>
</body>
</html>
推荐答案
由于你没有用jQuery标记这个,我我假设你不打算使用它。你仍然可以使用模板,即使没有它:
Since you didn't tag this with jQuery, I'll assume you aren't looking to use it. You can still use "templates" though, even without it:
将每个模板放在脚本标签中,类型=text / template:
Put each template in a script tag with type="text/template":
<script id="withIframe" type="text/template">
<p>With Iframe</p>
<video controls autoplay name="media">
<iframe width="420" height="315" <source src="https://www.youtube.com/embed/IdtKbq3Omkw" type="video/webm">
</iframe>
</video>
</script>
<script id="withoutIframe" type="text/template">
<p>Without Iframe</p>
<video controls autoplay name="media">
<source src="http://webmup.com/195a3/vid.webm" type="video/webm">
</video>
</script>
<div id="holder">
</div>
然后在你的javascript中根据你的逻辑加载正确的:
Then in your javascript load the correct one based on your logic:
var iframe = document.getElementById("withIframe").innerHTML;
var noiframe = document.getElementById("withoutIframe").innerHTML;
function myFunction() {
var chance = ((Math.random() * 100) + 1);
var output = '';
if (chance <= 50) {
output = noiframe;
} else {
output = iframe;
}
document.getElementById("holder").innerHTML = output;
}
myFunction();
注意,你的HTML中有一些拼写错误,你的条件总是会返回true:
Note, there were some typos in your HTML and you condition would always return true:
chance>= 0 || chance<=50
所有正数大于0 或小于50。
All positive numbers are greater than 0 or less than 50.
这是一个工作小提琴:
Here is a working fiddle: https://jsfiddle.net/mcgraphix/5cr4j1r7/
对于可以传入数据以填充模板的更复杂模板,您可能需要查看Mustache或把手。
For more complex templates where you can pass data in to populate your template, you may want to look at Mustache or Handlebars.
这篇关于内部的HTML代码< Script>标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!