2015-04-08 24 views
0

我嘗試從php文件中使用jquery將一段代碼放到我的index.php文件中。 我使用jQuery的函數load()來做到這一點,我沒有問題。jQuery load()函數插入非解釋代碼

問題是這段代碼沒有正確解釋。在這個例子中,我導入span,並看看這個跨度在index.php正確導入,我使用的jQuery click功能

,我想導入

//myText.php 

<?php 
    echo '<span>theSpan</span>'; 
?> 

的PHP代碼然後jQuery代碼

//scripts.js 

$(document).ready(function(){ 

    $(".my-php").load("myText.php"); 

    $("span").click(function(){ 
     alert("Success : it's a span !"); 
    }); 

}); 

的index.php的PHP

//index.php 

<body> 
    <div class="my-php"> 
    </div> 
</body> 

因此,當我點擊my-php div內的span時,我應該看到"Success : it's a span"。但沒有任何反應。跨度在這裏與文本'theSpan',但是當我點擊它時,沒有任何反應。

我試着解決這個問題,但這是一個非常奇怪的行爲。 我改變了jQuery代碼到:

$(document).ready(function(){ 

    var StrPhp = 'test'; 
    alert("1 - StrPhp : " +StrPhp); //Return 'test' 

    $(".my-php").load("myBets.php", function(str){ 
     StrPhp = str; 
     alert("2 - StrPhp : " +StrPhp); //Return '<span>theSpan</span>' 
    }); 

    $(".my-php").html(StrPhp); 

}); 

所以,我初始化變量StrPhp與'test'。 我試圖用StrPhp = str來捕捉load function的回調。 然後我嘗試將html function放在my-php div中。 它沒有工作。跨度與文本'theSpan'在這裏,但是當我點擊時,什麼都沒有。

但是!!

$(document).ready(function(){ 

    var StrPhp = 'test'; 
    alert("1 - StrPhp : " +StrPhp); //Return 'test' 

    $(".my-php").load("myBets.php", function(str){ 
     StrPhp = str; 
     alert("2 - StrPhp : " +StrPhp); //Return '<span>theSpan</span>' 
    }); 

    alert("3 - StrPhp : " +StrPhp); //Return 'test' 
    alert("4 - StrPhp : " +StrPhp); //Return '<span>theSpan</span>' !!! 
    $(".my-php").html(StrPhp); 

}); 

html() function之前有兩個警報,它的工作原理! 進入my-php div的跨度,並被解釋。我的意思是當我點擊它時,我可以看到"Success : it's a span"。 沒有這些警報,跨度不被jQuery解釋,當我點擊時,沒有任何反應。

很明顯,這是不固定的,因爲每次出現此問題時都不會使用警報。

所以,如果有人可以幫助我,它將不勝感激!

+0

的[爲什麼是我的變量不變後,我修改一個函數中可能重複? - 異步代碼引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Raidri

+0

tl; dr :'load()'函數是異步的 – Raidri

+0

無法將事件綁定到代碼運行時不存在的元素。要麼委派的事件或運行代碼時,元素確實存在 – charlietfl

回答

2

使用complete參數:

$(document).ready(function(){ 
    $(".my-php").load("myText.php",function() { 
    $("span").click(function(){ 
     alert("Success : it's a span !"); 
    }) 
    }); 
}); 
+0

很明顯,最後使用這個load不是這個Click函數,而是很多操作都不應該在這個Load中。這只是一個測試 – user2488028

+0

@ user2488028,然後在您的示例中提供更多真實世界的代碼。我們沒有水晶球來猜測你想要做什麼 – charlietfl

+0

@charlietfl我在說這麼說:如果我有很多點擊功能或其他功能,我必須在這個負載中複製所有內容? – user2488028

0

您可以使用jQuery.on這樣

$(document).ready(function(){ 

    $(".my-php").load("myText.php"); 
    $(".my-php").on('click','span',function(){ 
        alert("Success : it's a span !"); 
       }); 

});