【发布时间】:2020-06-02 05:58:38
【问题描述】:
script1.js 文件中的 jQuery 代码
$(document).ready(()=>{
$.ajax({
method:"GET",
url:"someurl",
success :
(data,status,xhr)=>{
//Create some html buttons after I get the data
//I want to append the js file here(the JavaScript file adds some event functions to the newly created buttons.I know i can add the event listeners to the button directly here but for some reason I prefer to have the code in a separate js file)
//This does not work
$('head'). append('<script src="script_here"></script>')
}
})
})
script2.js 文件中的 JavaScript 代码
document.addEventListener('DOMContentLoaded',ready)
function ready (){
document.querySelector('button').addEventListener('click',()=>{
//Do some other stuff
})
}
我尝试通过 jQuery 附加 script2.js 文件,但它不起作用。
我不想把所有东西都放在一个文件中以便于调试,我需要在我的项目中同时拥有 vanilla js 和 jQuery。
【问题讨论】:
-
在您的第二个脚本将其事件处理程序添加到文档之后,很可能没有发生 DOMContentLoaded 事件。
-
加载事件也不起作用..我的浏览器中也收到警告(不推荐使用主线程上的同步 xmlhttprequest jQuery.js,因为对最终用户体验有不利影响)当我有没有 DOMContentLoaded 和 Load 事件的脚本
-
所以请稍等片刻。为什么你认为你需要一个事件处理程序来处理这个逻辑,而不仅仅是运行逻辑?
-
你的意思是在script2.js中?
-
是的,你为什么需要那个?
标签: javascript jquery dom-events