[英]How to include a js file, on satistying the condition in jquery
<script> jQuery(document).ready(function(){ jQuery(".tabmenu li").click(function(){ var current_tab = jQuery(this).attr("class"); var res = current_tab.replace(" active_tab",""); if(res == 'tabmenu-8') { } }); }); </script>
I have a script, which is written above. 我有一个上面写的脚本。 What I want is, I want to include a js file on satisfying the if condition.
我想要的是,我想在满足if条件时包括一个js文件。 How can I do that?
我怎样才能做到这一点? I tried different methods I found while searching in google, but nothing helped me.
我尝试了在Google搜索时发现的不同方法,但没有任何帮助。
This is the script I want to add there 这是我要添加到的脚本
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
try this in if condition: 如果条件,请尝试以下操作:
var myscript = document.createElement('script');
myscript.setAttribute('src','http://code.jquery.com/jquery-1.9.1.js');
document.head.appendChild(myscript);
Adding additional scripts from JavaScript is actually quite easy. 从JavaScript添加其他脚本实际上非常容易。 Your create a script-element and set the type and src attributes and just add it to the head (or body, it doesn't really matter)
您创建一个脚本元素并设置type和src属性,然后将其添加到头部(或正文,这并不重要)
var newScript = document.createElement("script");
newScript.setAttribute("type","text/javascript");
newScript.setAttribute("src","http://code.jquery.com/jquery-1.9.1.js");
document.head.appendChild(newScript);
You can use .append()
: 您可以使用
.append()
:
$('head').append($('<script>').attr('type', 'text/javascript').attr('src', '//code.jquery.com/jquery-1.9.1.js'));
If you've included jQuery, it's better to use $.getScript() : 如果您已包含jQuery,则最好使用$ .getScript() :
$.getScript("http://code.jquery.com/jquery-1.9.1.js");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.