通过jQuery Not Functioning插入HTML

时间:2012-09-07 18:17:33

标签: javascript jquery html

我已经研究了使用javascript插入HTML的多种方法,使用jQuery .prepend和.innerHTML,无论我做什么,我都会得到相同的输出:

'); }

如果屏幕分辨率是一定宽度,我试图插入HTML。这些是我尝试过的两个脚本:

<script type="text/javascript" charset="utf-8" >

if (screen.width >= 500)
{
$('#stemanimation_hype_container').prepend('<script type="text/javascript" charset="utf-8" src="STEM%20Animation_Resources/stemanimation_hype_generated_script.js?58608></script>');

}
</script>

<div id="stemanimation_hype_container" style="position:relative;overflow:hidden;width:900px;height:300px;">
</div>

另一个:

<script type="text/javascript" charset="utf-8" >

if (screen.width >= 500)
{
document.getElementById("stemanimation_hype_container").innerHTML='<script type="text/javascript" charset="utf-8" src="STEM%20Animation_Resources/stemanimation_hype_generated_script.js?58608'></script>";

}

</script>
<div id="stemanimation_hype_container" style="position:relative;overflow:hidden;width:900px;height:300px;">
</div>

知道可能会发生什么吗?我在一个只有jquery的页面上测试它,没有其他脚本来确保没有冲突。谢谢你能给我的任何帮助!

8 个答案:

答案 0 :(得分:6)

您在定义要插入的html的字符串中有错误

'<script type="text/javascript" charset="utf-8" src="STEM%20Animation_Resources/stemanimation_hype_generated_script.js?58608'></script>";

应该是:

'<script type="text/javascript" charset="utf-8" src="STEM%20Animation_Resources/stemanimation_hype_generated_script.js?58608"></script>';

答案 1 :(得分:1)

"

之后,您的第一段代码遗失了?58608

您的第二个代码块有一个',其中"之后应该有?58608,而字符串末尾应该有$('#stemanimation_hype_container').prepend('<script type="text/javascript" charset="utf-8" src="STEM%20Animation_Resources/stemanimation_hype_generated_script.js?58608"></script>');

尝试

{{1}}

答案 2 :(得分:1)

您的原始代码很好,但是这个错误:

..._script.js?58608"></script>');
                // ^ Forgot a "

或者,我可能会建议使用document.createElement并将其附加到容器中:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '..._script.js?58608';
document.getElementById('stemanimation_hype_container').appendChild(script);

或者,jQuery方式:

$('<script>',{
  'type' : 'text/javascript',
  'src' : '..._script.js?58608'
}).appendTo('#stemanimation_hype_container');

(注意我在代码中使用...是为了简洁,而不是准确性)

答案 3 :(得分:0)

你试过这个:

$('#stemanimation_hype_container').html('<script type="text/javascript" charset="utf-8" src="STEM%20Animation_Resources/stemanimation_hype_generated_script.js?58608"></script>');

答案 4 :(得分:0)

如果你发布的代码是你正在尝试的实际代码,你在jq示例中有一个不匹配的双引号,而在另一个版本中有一个double关闭一个。

答案 5 :(得分:0)

在两个示例中,我看到src属性中引号的使用不一致。你从双引号开始,但以单引号结束。尝试用双引号结束它。

答案 6 :(得分:0)

您需要将脚本块放在HTML的末尾。现在,在将div插入DOM之前,您正在寻找$('#stemanimation_hype_container'),因此在运行JS时它不存在。这就是没有任何反应的原因。

答案 7 :(得分:0)

让我正常工作的问题实际上是与Tumult Hype的CSS3动画脚本的一个讨厌的冲突。除了关于双引号的拼写错误之外,代码示例实际上对大多数应用程序都是正确的。