views:

325

answers:

1

My website contains links and when I click on a click, the target HTML content is loaded into a "div" using JQuery, no problem so far.

My problem is when my search page below is loaded for the third time, the script will not execute:

<h1><span>Search</span></h1>
<p class="bigtext">Entity</p>
<input type="text" id="searchfield">
<p class="more">
    <a href="#">Find</a>
</p>
<p></p>
<div id="res"></div>

<script type="text/javascript">
    alert("hello");
</script>

Observe that the script works for the two first times, but not for the third time. I have also tried changing the position etc, but no postive results. The problem only occurs for the search page, the HTML content is loaded, I also see the script using Firebug, but it won't execute the alert().

My general load-into-div script is this:

<script type="text/javascript">
$(document).ready(function()
{
    var page = "blog";

    $('a').click(function()
    {
        var id = $(this).attr("id");
        if ( id != null && id !="" )
        {
            page = "index.php/"+id;
            $("#inc").load(page);
        }
    });

    setInterval(function() {
        if (page=="index.php/toplist")
            $("#inc").load(page);
    }, 6000);
});
</script>

Any suggestions on how to solve this problem? Thanks in advance.

// Hirre

+2  A: 

Loading HTML with <script> elements into the page is basically unreliable. jQuery takes a number of steps to try to make it work cross-browser, but in several cases jQuery fails.

So don't rely on it. Keep your script content in the basic script instead, run from callback after loading if necessary.

bobince
Can you give an example please.
Hirre
It depends what your code is doing. For the basic case posted above it would be easy to do the alert in a callback: `$("#inc").load(page, function() { alert('hello!'); });`.
bobince
problem solved :)
Hirre