jQuery:选择器不能处理ajax加载的内容

时间:2013-11-15 18:00:17

标签: javascript php jquery html css

这是一个简单的脚本,我希望sum1调试并报告我的错误。

<html>

    <head>
        <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
        <script>
            $(document).ready(function() {
                $("#content1").click(function() {
                    $("#content2").load("test.php");
                });
                $("span").click(function() {
                    $(this).css("font-size", "30px");
                });
            });
        </script>
    </head>

    <body>
        <div id="content1">Click to load content2</div>
        <div id="content2"></div>
    </body>

</html>

- test.php--

<span>Click to format content 2&#60;/span><br>

现在我的问题是span的选择器不起作用。

3 个答案:

答案 0 :(得分:3)

活动授权:

$("#content2").on("click", "span", function()

答案 1 :(得分:0)

试试这个:

$("body").on("click","span",function(){
    $(this).css("font-size","30px");
});

答案 2 :(得分:0)

只需在$(“#content2”)的成功事件中添加span click函数.load function

这样,只有在将新跨度加载到页面后才会触发新的跨度单击绑定功能,因此单击事件也会应用于新跨度。

 <script>
            $(document).ready(function() {
                $("#content1").click(function() {
                    $("#content2").load("test.php",function(){

                       // Now the click event is assigned after the span is loaded.
                       // Hence its applied to newly loaded span as well
                       $("span").click(function() {
                         $(this).css("font-size", "30px");
                       });

                    });
                });

            });
</script>

干杯.. !!