且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

& lt; Script& gt;中的HTML代码标签

更新时间:2022-12-04 22:06:00

由于您没有使用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.***.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.