在 AJAX 请求后重新加载 javascript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8594408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:38:12  来源:igfitidea点击:

Reload javascript file after an AJAX request

javascriptjqueryajax

提问by Micha?l

After the request, the new elements created are not recognized by the event handlers in my jQuery code.

在请求之后,我的 jQuery 代码中的事件处理程序无法识别创建的新元素。

Is there a way to reload the file to re-register these events?

有没有办法重新加载文件以重新注册这些事件?

回答by StuperUser

I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?

我假设您的意思是您为已被 ajax 请求结果替换的元素注册的事件没有触发?

Use .live()(see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.

使用.live()(参见http://api.jquery.com/live/)针对与选择器匹配的元素(包括从 ajax 的结果创建的新 DOM 元素)注册事件,而不是选择器的结果事件处理程序是第一个,当它们被替换时将被销毁。

e.g. replace

例如替换

$('div.someClass').click(function(e){
    //do stuff
});

with

$('div.someClass').live('click', function(e){
    //do stuff
});

Important:

重要的:

While I've recommended using .live()this is for clarity as its syntax is similar to .bind(), you should use .on()if possible. See links in @jbabey's comment for important information.

虽然我建议使用.live()this 是为了清楚起见,因为它的语法类似于.bind(),但您应该.on()尽可能使用。有关重要信息,请参阅 @jbabey 评论中的链接。

回答by Micha?l

This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div>bloc and want to catch the onClick event.

这个问题是关于在页面加载后创建的 DOM 元素上绑定事件处理程序。例如,如果在请求 ajax 之后您创建了一个新<div>块并想要捕获 onClick 事件。

//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
    //do stuff
});

// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
    //do stuff
});

// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
    //do stuff
});

You would find the documentation here: http://api.jquery.com/on/

您可以在此处找到文档:http: //api.jquery.com/on/

回答by Omar Abou Elmagd

This codes works perfect for me..

这段代码非常适合我..

$("head script").each(function(){
            var oldScript = this.getAttribute("src");
            $(this).remove();
            var newScript;
            newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            newScript.src = oldScript;
            document.getElementsByTagName("head")[0].appendChild(newScript);
        });

It removes the old script tag and make a new one with the same src (reloading it).

它删除旧的脚本标签并使用相同的 src 创建一个新标签(重新加载它)。

回答by Abhijit Jagtap

To increase the website performance and reduce the total file's size return, you may consider to load JavaSript (.js) file when it's required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.

为了提高网站性能并减少总文件的大小返回,您可以考虑在需要时加载 JavaSript (.js) 文件。在 jQuery 中,您可以使用 $.getScript 函数在运行时或按需加载 JavaScript 文件。

For example,

例如,

$("#load").click(function(){
    $.getScript('helloworld.js', function() {
        $("#content").html('Javascript is loaded successful!');
    });
});

when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.

当一个 Id 为“load”的按钮被点击时,它会动态加载“helloworld.js”JavaScript 文件。

Try it yourselfIn this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.

自己尝试在这个例子中,当你点击加载按钮时,它会在运行时加载“js-example/helloworld.js”,其中包含一个“sayhello()”函数。

<html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

</head>
<body>
  <h1>Load Javascript dynamically with jQuery</h1>

<div id="content"></div>
<br/>

<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>

<script type="text/javascript">

$("#load").click(function(){
  $.getScript('js-example/helloworld.js', function() {
     $("#content").html('
          Javascript is loaded successful! sayHello() function is loaded!
     ');
  });
});

$("#sayHello").click(function(){
  sayHello();
});

</script>
</body>
</html>

回答by Dan185

You can also attach the click handlers to the body so that they never get destroyed in the first place.

您还可以将点击处理程序附加到主体,以便它们永远不会首先被破坏。

$('body').on('click', 'a', function(event) {
  event.preventDefault();
  event.stopPropagation();
  // some stuff
})

回答by bnassim

  var scripts = document.getElementsByTagName("script");
  for (var i=0;i<scripts.length;i++) {
    if (scripts[i].src)
      if(scripts[i].src.indexOf('nameofyourfile')  > -1 )
        var yourfile = scripts[i].src;
  }
  jQuery.get(yourfile, function(data){
  if(data){
     try {
      eval(data);
     } catch (e) {
     alert(e.message);
    }
 }
    });

回答by Arun jai

You can try loadscript plugin for loading the javascript file.

您可以尝试使用 loadscript 插件加载 javascript 文件。

forexample 
$("#load").click(function(){
    $.loadScript('path/example.js');
});

or 
$.ajax({
   success: function(data) {
        $.loadScript('path/example.js');
   }
});

http://marcbuils.github.io/jquery.loadscript/

http://marcbuils.github.io/jquery.loadscript/

回答by orolo

In your request callback, call a function that acts on your newly appended or created blocks.

在您的请求回调中,调用一个作用于您新添加或创建的块的函数。

$.ajax({
   success: function(data) {
        $('body').append(data);
        //do your javascript here to act on new blocks
   }
});

回答by user3176429

simple way to solve this problem

解决这个问题的简单方法

$(document).ready(function(){

$('body').on('click','.someClass',function(){

//do your javascript here..

});
}); 

回答by Tony Bogdanov

What do you mean not recognized by jQuery?

jQuery 无法识别是什么意思?

jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.

每次发出请求时,jQuery 都会遍历 DOM,因此它们应该是可见的。然而,附加的事件不会。

What isn't visible exactly?

什么是不可见的?

P.S.: Reloading JavaScript is possible, but highly discouraged!

PS:重新加载 JavaScript 是可能的,但非常不鼓励!