weixin_33725515 2015-11-18 19:58 采纳率: 0%
浏览 21

在ajax回调中创建链接

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/203198/event-binding-on-dynamically-created-elements" dir="ltr">Event binding on dynamically created elements?</a>
                            <span class="question-originals-answer-count">
                                (23 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-11-19 00:16:24Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

I create a link in ajax callback function and define a class for that, commands that I write on click of this link doesn't work. the code is here:

$('.catpics').click(function(){
   var id=$(this).attr('id');
   $.post('storehouse.php', {
     catid:id,
     btn:'showsub'
   },function(data){
     $('#subcatshelf').append('<a class="catpics" id="'+ data+'">'+data+'</a>');
   });
</div>
  • 写回答

1条回答 默认 最新

  • weixin_33686714 2015-11-18 20:08
    关注

    $('.catpics').click(function(){ only binds to links once. You're looking for .on which will bind to the first object you give it (so you can give it the body of your webpage) and then tell it to listen for clicks on .catpics and since the listener is on the body and not the individual .catpics elements, it wont matter when the links are actually inserted or deleted:

    $('body').on('click', '.catpics', function() {
       var id=$(this).attr('id');
       $.post('storehouse.php', {catid:id,btn:'showsub'},function(data){
         $('#subcatshelf').append('<a class="catpics" id="'+ data+'">'+data+'</a>');
       });
    });
    

    alternatively you can make click work just fine by pulling out the event handler and just setting up a new clicked listener as you insert a new link:

    function clickedCatPic() {
       var id=$(this).attr('id');
       $.post('storehouse.php', {catid:id,btn:'showsub'},function(data){
         var link = $('<a class="catpics" id="'+ data+'">'+data+'</a>');
         $('#subcatshelf').append(link);
         link.click(clickedCatPic);
       });
    }
    
    $('.catpics').click(clickedCatPic);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 python忆阻器数字识别
  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真