【问题标题】:jQuery load() function inserts non-interpreted codejQuery load() 函数插入非解释代码
【发布时间】: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 不会解释跨度,当我单击时,什么也不会发生。

显然,这不是固定的,因为每次遇到此问题时我都不想使用警报。

所以如果有人可以帮助我,将不胜感激!

【问题讨论】:

标签: php jquery function load alert


【解决方案1】:

使用complete参数:

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

【讨论】:

  • 显然,这个load最终使用的不是这个Click函数,而是很多不应该在这个Load中的操作。这只是一个测试
  • @user2488028 然后在您的示例中提供更多真实世界的代码。我们没有水晶球来猜测您要做什么
  • @charlietfl 我的意思是说:如果我有很多点击功能或其他功能,我必须在这个负载中复制所有内容?
  • @user2488028 不,你可以使用事件委托learn.jquery.com/events/event-delegation
  • 非常感谢您的回答! @charlietfl
【解决方案2】:

你可以像这样使用jQuery.on

$(document).ready(function(){

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

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2012-10-15
    • 2013-08-13
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多