通过jQuery插入HTML不起作用

Insert HTML By jQuery Not Functioning

本文关键字:不起作用 HTML 插入 jQuery 通过      更新时间:2023-09-26

我已经研究了用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而没有其他脚本的页面上测试这一点,以确保没有冲突。谢谢你能给我的任何帮助!

您在定义要插入的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>';

您的第一个代码块在?58608 之后缺少"

您的第二个代码块有一个',其中?58608之后应该有",反之亦然。

尝试

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

您的原始代码很好,但此错误:

..._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');

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

如果您发布的代码是您正在尝试的实际代码,那么在jq示例中会有一个不匹配的双引号,在另一个版本中会有双引号。

你试过这个吗:

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

在这两个例子中,我看到src属性中引号的使用不一致。你以双引号开始,但以单引号结束。试着用双引号结尾。

您需要将脚本块放在HTML的末尾。现在,在将div插入DOM之前,您正在查找$('#stemmanimation_hype_container'),因此在运行JS时它不存在。这就是为什么什么都没发生。

我想让它正常工作的问题实际上是与Tumult Hype的CSS3动画脚本发生了严重冲突。除了我在双引号方面的拼写错误外,这些代码示例实际上对大多数应用程序都是正确的。