【发布时间】:2015-04-08 12:09:11
【问题描述】:
我尝试使用 jquery 将 php 文件中的一段代码放入我的 index.php 文件中。
我使用 jQuery 的函数load() 来做到这一点,我对此没有任何问题。
问题是这段代码没有被正确解释。在这个例子中,我导入了一个span,为了查看这个span是否正确导入到了index.php中,我使用了jQuery click函数
我要导入的php代码
//myText.php
<?php
echo '<span>theSpan</span>';
?>
然后是 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);
});
所以,我用'test' 初始化了一个变量 StrPhp。
我尝试用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 不会解释跨度,当我单击时,什么也不会发生。
显然,这不是固定的,因为每次遇到此问题时我都不想使用警报。
所以如果有人可以帮助我,将不胜感激!
【问题讨论】:
-
tl;dr:
load()函数是异步的 -
无法将事件绑定到代码运行时不存在的元素。当元素确实存在时委托事件或运行代码
-
换句话说,当你告诉专业人士...... ^他说什么
标签: php jquery function load alert