我嘗試從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解釋,當我點擊時,沒有任何反應。
很明顯,這是不固定的,因爲每次出現此問題時都不會使用警報。
所以,如果有人可以幫助我,它將不勝感激!
的[爲什麼是我的變量不變後,我修改一個函數中可能重複? - 異步代碼引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Raidri
tl; dr :'load()'函數是異步的 – Raidri
無法將事件綁定到代碼運行時不存在的元素。要麼委派的事件或運行代碼時,元素確實存在 – charlietfl