开发者

loading a function onclick

I have the following piece of code

<a onclick="$('#result').load('codes/test.html');$('#result').show();" >XHTML code</a>

it loads perfectly the content of test.html in the result div and 开发者_开发问答also make it visible. Until this point all are good. When I try to add a function prettyPrint() which apply some modifications on the text and change the code to the following:

<a onclick="$('#result').load('codes/test.html');$('#result').show();prettyPrint();" >XHTML code</a>

I can't make the prettyPrint() to work, instead if I add onmouseout="prettyPrint(); it works when I take off my cursor. I don't have experience with javascript and jquery so I don't know what is the real problem, so I would appreciate any help on how to make prettyPrint to work onclick.


If you are using jQuery why do you bother with inline Javascript? Why not:

<script type="text/javascript">
$(function(){
    $('#myLink').click(function(){
        $('#result').load('codes/test.html', function() {
            $('#result').show();
            prettyPrint();
        });

        return false;
    });
}):
</script>

<a id="myLink" href="#">XHTML code</a>

Edit:

Fixed code so it calls prettyPrint() when load callback is called.


The load is asynchronous. When prettyPrint is called, the text might not be there yet.

<a onclick="$('#result').load('codes/test.html', function(){prettyPrint();$('#result').show();});" >XHTML code</a>

load() takes a second argument which is a function to call when the load is done. I moved the prettyPrint and the show to there.


You can do the following:

$('#result').show("fast",function(){ prettyPrint();});


You should use a callback function:

<a onclick="$('#result').load('codes/test.html', function() {prettyPrint();}).show();" >XHTML code</a>


Your problem is that you misunderstand how .load() works. It does not block until the data is loaded. Instead, it only starts loading and returns immediately. Therefore, your prettyPrint function gets called when the data is not loaded yet.

To fix this, pass a callback function to .load. That callback will be called when the load completes:

$("#result").load( '...',
    function() { 
        $("#result").show();
        prettyPrint();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜