简体   繁体   English

推迟执行javascript,直到将内容添加到Document中为止

[英]Defer javascript execution till the content has been added to Document

I am trying to load some content into a page using Ajax. 我正在尝试使用Ajax将一些内容加载到页面中。 The html that is loaded contains some javascript code. 加载的html包含一些javascript代码。 Even though the code is wrapped within $(document).ready , it gets executed before the content is inserted into the document, because the parent document's Dom is ready by the time the content is loaded. 即使代码被包装在$(document).ready ,它也会在内容插入文档之前执行,因为在加载内容时父文档的Dom已准备就绪。

How can I defer the execution of the code, until the content has been inserted into the document. 在将内容插入文档之前,如何才能推迟执行代码。 Here is the html that I am trying to load (this is the code for openid-selector ) 这是我要加载的html(这是openid-selector的代码)

<script type="text/javascript" src="/js/openid-jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    alert('ajax-html');
    openid.init('openid_identifier');
});
</script>
<!-- Simple OpenID Selector -->
<form action="try_auth.php" method="get" id="openid_form">
    <input type="hidden" name="action" value="verify" />

    <fieldset>
            <legend>Sign-in or Create New Account</legend>

            <div id="openid_choice">
                <p>Please click your account provider:</p>
                <div id="openid_btns"></div>
            </div>

            <div id="openid_input_area">
                <input id="openid_identifier" name="openid_identifier" type="text" value="http://www.joycebabu.com" />
                <input id="openid_submit" type="submit" value="Sign-In"/>
            </div>
    </fieldset>
</form>

Update : Removed the noscript tag 更新 :删除了noscript标签

It seems that the problem is that openid.init() is loading its own data and you want to manipulate that data after it has been loaded synchronously. 看来问题在于openid.init()正在加载自己的数据,并且您希望在同步加载数据后对其进行操作。 There are a couple solutions: 有两种解决方案:

Associate a callback function that executes when the asynchronous load is complete. 关联在异步加载完成后执行的回调函数。 Does the openid lib not offer you this functionality? openid库不为您提供此功能吗?

If you know the valid selectors of the data elements you want to manipulate before they've been added to the DOM, you can use .live() . 如果在将数据元素添加到DOM之前知道它们要操作的有效选择器,则可以使用.live()

I notice you are using the noscript tag. 我注意到您正在使用noscript标签。 I advise against this strongly. 我强烈建议不要这样做。 Do all of your DOM manipulation through JS. 通过JS完成所有DOM操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM