Javascript won't execute after load

北城以北 提交于 2020-01-11 12:57:07

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/2176279/javascript-wont-execute-after-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!