开发者

jQuery .load() with scripts

I know this question has been asked but I haven't found any satisfactory answers. I have a very simple html page that I want to load into a number of other pages. That's no problem but where I'm getting stuck is that this html page has one jQuery hover function that simply will not execute on the other pages. I've tried putting the hover function on each page, I've tried .getScript. From what I understand, jQuery will load the scripts from the .load() page, execute them, then remove them. But since it's a hover function I nee开发者_运维技巧d those scripts to stay around. Is there any way I can do this? I'll post the code if necessary but it works perfectly so I don't think it's that...

on each page:

    if ($("#zz7_Menu:contains('myname')")) {
    $("#toolbar").load('toolbar.html table.toolbaradmin');
}
else {
    $("#toolbar").load('/toolbar.html table.toolbar');
}

toolbar.html:

<script type="text/javascript" src="scripts/jquery-1.6.2.min.js"></script>
<link rel="stylesheet" href="jquery-ui/css/redmond/jquery-ui-1.8.13.custom.css" type="text/css" media="all" />

<script>
    $(document).ready(function() {
    $('.ui-state-default').hover(function() {
        $(this).removeClass('ui-state-default').addClass('ui-state-hover');
    },
    function() {
        $(this).removeClass('ui-state-hover').addClass('ui-state-default');
    });
    });
</script>

<table class="toolbar">
    <tr>
        <td class="ui-state-default ui-corner-all toolbar">

etc...


Try to move the hover code into a standalong JavaScript file (which you can load everywhere with <script src="...">).

Now use jQuery to install the hover function call again after .load() has completed successfully. After extracting, this should be a single line of code.


Move the javascript that affects the table to AFTER the table. Since the document is already ready, it gets ran immediately, which happens to be before the table is added to the page. Also, if jquery is included in the parent page already, you don't need to include jquery in the page you are loading.

<table>
  <!-- ... table stuff ... -->
</table>
<script>
    $(document).ready(function() {
    $('.ui-state-default').hover(function() {
        $(this).removeClass('ui-state-default').addClass('ui-state-hover');
    },
    function() {
        $(this).removeClass('ui-state-hover').addClass('ui-state-default');
    });
    });
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜