如何将jQuery脚本附加到head标签 [英] How to append a jQuery script to head tag

查看:146
本文介绍了如何将jQuery脚本附加到head标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当窗口尺寸小于580px时,我试图在我的head标签中附加带有src属性的jQuery脚本.

I'm trying to append a jQuery script with src attributes in my head tag when the window size is less of 580px.

我尝试使用以下代码:

<script>
    $(document).ready(function(){
        var windowSize = $(window).width();
        if( windowSize > 300 && windowSize < 570) {
            $('head').append('<script src=\"http://code.jquery.com/jquery-1.11.3.min.js\" type="text/javascript\"><\/script>');     
        }
    });
</script>

但是似乎不起作用. 相反,我在脚本中放了一个简单的警报,它起作用了:

But it seems it doesn't work. Instead, I put inside the script a simple alert and it works:

<script>
    $(document).ready(function(){
        var windowSize = $(window).width();                 
        if( windowSize > 300 && windowSize < 570) { 
            $('head').append('<script>alert("hi");<\/script>');
        }
    });
</script>

我认为问题是src =".我应该做些什么?

I think the problem is the src="". What am I supposed to do?

推荐答案

我看到此代码有2个问题:

I see 2 problems with this code:

1)您正在脚本块中使用jQuery语法来添加引用以加载jQuery吗?除非您已经在某处加载了jQuery副本,并且出于某种原因试图使用此代码将其更新为其他版本,否则这将无法工作.

1) You are using jQuery syntax in your script block to add a reference to load jQuery? This will NOT work unless you already have a copy of jQuery loaded somewhere and are trying to use this code to update it to something else for some reason.

2)我看到您正在像这样转义":在您的第一个示例中,是\".假设问题1确实不是问题或已解决,则您无需在jQuery中执行此操作. jQuery将正确处理单引号内的双引号,反之亦然.

2) I see you are escaping the " like so: \" in your first example. You DO NOT need to do that in jQuery, assuming issue 1 is not really an issue or resolved. jQuery will properly handle double quotes inside a single quote or vice versa.

这篇关于如何将jQuery脚本附加到head标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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