& lt; Script& gt;中的HTML代码标签 [英] HTML code inside <Script> tag

查看:48
本文介绍了& lt; Script& gt;中的HTML代码标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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:

将每个模板放入具有type ="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.

这是一个有效的小提琴: https://jsfiddle.net/mcgraphix/5cr4j1r7/

Here is a working fiddle: https://jsfiddle.net/mcgraphix/5cr4j1r7/

对于可以在其中传递数据以填充模板的更复杂的模板,您可能需要查看Mustache或Handlebars.

For more complex templates where you can pass data in to populate your template, you may want to look at Mustache or Handlebars.

这篇关于&amp; lt; Script&amp; gt;中的HTML代码标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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