开发者

How to inherit parent javascript with jQuery ajax

I am using jQuery.ajax to call a script that renders results to html snippet and it is loaded into a div, something like this:

jQuery.ajax({type:'POST',data:{'var': '1'}, url:'/some/script',success:function(data,textStatus){jQuery('#myDiv').html(data);}});

Script executes and page loads into my div. The pr开发者_StackOverflow社区oblem / dilemma that I have is that my parent page (the page I call ajax from) has a few jquery scripts included in the header, that are run on page load, for example date picker, labelify, ui.selectmenu select box and a few more. However, once my child page loads it does not inherit styles/functionality applied by those scripts. I understand that it is because those scripts are executed on parent page load and are not triggered when child page loads. Questions:

  1. Should a child HTML page be a complete HTML page with its own header and body and include all the needed scripts, even though same scripts are being included in the parent. (right not child page is just an html snippet)

  2. If It should not be a complete HTML page, then should I include all my scripts anyways in the body of the child page (html snippet)

  3. Is there an easy way to trigger all jquery parent scripts on child load. Basically faking page load for parent.

Any other ideas suggestions?

Thanks!


If you put the script you want running in a document onload inside your included file, it will run with the parent's scripts when the content is loaded in.

Make a new file with this in it, and load it in to your parent file to see. Don't include the jQuery script in the child file, so it doesn't have access to the $(document) on its own.

<script type="text/javascript">
$(document).ready(function(){
    alert('a');
});
</script>

To make any run-on-load-code from the parent apply to the child, you'll probably have to create a function that does everything in the parent, and allow the child to call it when it loads in.

Current parent:

<script>
    $(document).ready(function(){ doSomething(); doSomethingElse(); });
</script>

becomes...

<script>
    $(document).ready(function(){ loaded(); });
    function loaded () { doSomething(); doSomethingElse(); }
</script>

Then in the child, it calls $(document).ready(function(){ loaded(); }); as well.


If you're looking for event handlers, try jQuery.live. If you have generic ui stuff at onload, like

$(".datepicker").datepicker();

try wrapping it into a function with a certain focus:

function doLayout(focus)
{
$(focus).find(".datepicker").datepicker();
}

Now you can call doLayout("#myDiv") as soon as AJAX content has been loaded. For $.ready use doLayout("body").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜