21

随着开发的不断深入,这两天在Yii框架下利用jQuery实现了AJAX。关键点有如下:

//listen to main element with ajaxlink style class name
    $(document).ready(function(){
        //after clicking a prediction intro
       $('.ajaxlink').click(function(){
           //ajax scan all dom element at the begining
           //and will not scan again even if class name is changed
           //so need to check the class name for sure
           if($(this).attr('class')=="ajaxlink"){
            targetID=$(this).attr('pid');
            $.ajax({
                type:"POST",
                url:'index.php?r=prediction/load',
                data:"id="+targetID,
                success:function(data){
                    $('#detail_'+targetID).html(data);
                }
            })
           }
        });
    });

核心是初始化文档时侦听带有特定样式名的元素,如果它(们)被点击,则激发js函数进行处理。这里是把id以post的形式发送到index.php?r=prediction/load,并将返回值放到id为#detail_x的元素中。实际开发过程中发现jQuery建立侦听后不能再添加侦听或者消除已建立的侦听,即使改变了样式名也不行。所以上面代码中加了一个对样式名的判断,虽然改变样式名不能消除侦听,但可以通过判断不执行相应操作。

Tags:

1 Response

Leave a Response

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">