我有 contactus.js
,其中定义了 sendMail(to)
函数。
我有main.js
:
...
$('#ContactUs').click(function(){
// how to execute /contactus.js, and when done, send mail?
sendMail(to);
});
...
但是,由于 main.js
用于网站的每个 HTML 页面,因此我不喜欢在 main.js 之前包含
,以免加载无用的脚本。contactus.js
仅当单击#contactus 时,我才需要加载(执行)contactus.js。
编辑:
我在这里添加了一个Fiddle,来演示效果:
$(function() {
console.log("ready!");
$('#submit').click(function() {
console.log("click start");
$.getScript("http://parsleyjs.org/dist/parsley.js", function() {
console.log("the object is: " + window.parsley);
});
console.log("click end");
});
});
<form action="alert('done');" id="myForm">
<input type="email" required>
<div id="submit">submit</div>
</form>
最佳答案
使用jQuery.getScript ,如下所示。
Load a JavaScript file from the server using a GET HTTP request, then execute it.
$('#ContactUs').click(function(){
// how to execute /contactus.js, and when done, send mail?
$.getScript("/contactus.js", function() {
sendMail(to);
});
});
关于javascript - 在 jquery 中导入另一个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29342551/