簡體   English   中英

jQuery.load() html 頁面,里面有 javascript

[英]jQuery .load() html page with javascript inside

我在將.html 頁面(內部有 JavaScript)加載到 div 元素時遇到問題。

這是我的 div:

<div class="content"></div>

這是我的 php:

<?php
  if(!$_POST['page']) die("0");
  $page = (int)$_POST['page'];
  if(file_exists('pages/page_'.$page.'.html'))
    echo file_get_contents('pages/page_'.$page.'.html');
  else echo 'There is no such page!';
?>

這是我的腳本:

var default_content="";
$(document).ready(function(){   
checkURL();
$('ul li a').click(function (e){
        checkURL(this.hash);
}); 
//filling in the default content
default_content = $('.content').html();     
setInterval("checkURL()",250);  
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;    
if(hash != lasturl)
{
    lasturl=hash;       
    // FIX - if we've used the history buttons to return to the homepage,
    // fill the pageContent with the default_content        
    if(hash=="")
    $('.content').html(default_content);        
    else
    loadPage(hash);
}
}

function loadPage(url)
{
url=url.replace('#page','');    
$('.content').css('visibility','visible');  
$.ajax({
    type: "POST",
    url: "load_page.php",
    data: 'page='+url,
    dataType: "html",
    success: function(msg){         
        if(parseInt(msg)!=0)            
        {
            $('.content').html(msg);        
        }
    }       
});
 }

加載頁面時,不會執行 html 頁面內的 JavaScript 代碼。 如果我單擊瀏覽器重新加載按鈕,則會執行 JavaScript 代碼。

如何使用 jquery 在頁面內執行 JavaScript?

你的腳本沒有意義

$.ajax({
    type: "POST",
    url: "load_page.php",
    data: 'page='+url,
    dataType: "html",
    success: function(d){
        $('.content').html(d);        
    }       
});

更好,將執行從 ajax 加載的 javascrit 頁面

jQuery 事件處理程序是否與live()綁定?

http://api.jquery.com/live/

如果在頁面加載后將 javascript/jquery 附加到 dom,則不會附加/執行正常的click()change()事件。

您需要使用live()附加這些事件。

$('#some_element').live('click', function(){});

每當元素附加到頁面時, live()都會初始化事件處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM