【问题标题】:My JavaScript code won't run after jquery ajax call我的 JavaScript 代码在 jquery ajax 调用后不会运行
【发布时间】: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 事件。
  • 加载事件也不起作用..我的浏览器中也收到警告(不推荐使用主线程上的同步 xm​​lhttprequest jQuery.js,因为对最终用户体验有不利影响)当我有没有 DOMContentLoaded 和 Load 事件的脚本
  • 所以请稍等片刻。为什么你认为你需要一个事件处理程序来处理这个逻辑,而不仅仅是运行逻辑?
  • 你的意思是在script2.js中?
  • 是的,你为什么需要那个?

标签: javascript jquery dom-events


【解决方案1】:

如果你只是想在 ajax 调用之后加载一个外部 js 文件。然后我将向您展示如何在 Pure JS 中使用。由于我遇到过类似的问题,所以它可能会帮助你。

(data,status,xhr)=>{
    const fileref = document.createElement('script');
    fileref.setAttribute('type', 'text/javascript');
    fileref.setAttribute('src',
    'https://speechanywhere.nuancehdp.com/3.0/scripts/Nuance.SpeechAnywhere.js?_r=' +
    (Math.random() * Math.pow(10, 18)).toString(32)); // the math random will help from cache errors each time you load
    document.getElementsByTagName('head')[0].appendChild(fileref);
}

Import and use external JS Library

【讨论】:

  • document.head 已经可以访问了。同document.body
猜你喜欢
  • 2012-03-03
  • 1970-01-01
  • 2021-05-12
  • 2017-06-19
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多