强制脚本在AJAX加载页面中运行 [英] Forcing Script To Run In AJAX Loaded Page

查看:47
本文介绍了强制脚本在AJAX加载页面中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在WP安装中使用的是AJAX加载程序,并且正在加载的页面之一中包含脚本.

So I am using an AJAX loader on my WP installation and one of the pages I am loading has a script in it.

<div id="register-form">
    <div id="register-one"></div>
    <div style="text-align:center;padding-top:10px;"></div> 
    <div class="horizontal-rule"></div>
    <div id='register'>
        <div id="register-character">
        </div>
    </div>

    <div class="post">  
        <form action="" method="post" id="register-form" >
        What's your Name:
            <input class=in id='register_name' name="register_name" onkeydown='register_step1_keydown();' onkeyup='register_step1_keyup();'>
            <input class="next-submit-button" type="submit" id="register-step-one" value="" />
            <input type="hidden" name="submit" />
        </form>  
    </div>
</div>

<script type="text/javascript">

$("#register-step-one").click(function() {
    $.ajax({
      type: "POST",
      success: function() {
        $('#register-form').html("Test");
      }
     });
    return false;
});

</script>

问题是,当通过AJAX加载页面时,脚本不起作用.但是,如果刷新页面,该脚本将起作用.显然,脚本不喜欢通过AJAX调用运行.

The issue is however, when the page is loaded through the AJAX, the script doesn't work. Yet if I refresh the page the script works. Obviously the script doesn't like running from an AJAX call.

通过AJAX调用加载脚本时,是否可以使脚本正常工作?我知道我可以将脚本放到主页的页脚或其他位置,但是我希望能解决这个问题,因为最终我会在主页上放置大量脚本.

Is there a way to make the script work when it is loaded through an AJAX call? I know I could put the script in to the main page's footer or something but I was hoping I could get around this as I will end up with a ton of scripts in the main page.

推荐答案

在进行任何其他操作之前,应将函数包装在.ready()中,以确保在对这些元素执行某些操作之前,已加载所有DOM元素

Before anything else, you should wrap your function in a .ready() to ensure all DOM elements are loaded before you do something to those elements

此外,仅当HTML附加在DOM中时,才会执行通过jQuery中的ajax函数返回的HTML中的脚本.由于您未附加包含代码的html,因此返回的内容中的脚本将无法运行.

Also, scripts within HTML that are returned via ajax functions in jQuery are executed only when the HTML is appended in the DOM. Since you did not append the html containing the code, the script in that returned content won't run.

dataType <下,查看 .ajax() 函数的参数/p>

Take a look at the .ajax() function's parameters, under dataType

数据类型:

...

" html" ;:以纯文本格式返回HTML;否则,返回HTML.当插入DOM中时,评估包含的脚本标签.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

...

这篇关于强制脚本在AJAX加载页面中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆