且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery:当绑定/单击事件用于类时,引用调用对象(this)

更新时间:2022-06-27 00:20:35

$(this)仅在函数范围内相关。但是在函数之外,它会丢失该引用:

$(this) is only relevant within the scope of the function. outside of the function though, it loses that reference:

$('.classSelect').one("click", function() {
   $(this); // refers to $('.classSelect')

   $.ajax({
   // content
      $(this); // does not refer to $('.classSelect')
   });
});

处理此问题的更好方法可能是:

a better way to handle this may be:

$('.classSelect').one("click", function() {
    var e = $(this);

    $.ajax({
    ...
        success : function(request) {
          e.html(request);
        }
    }); // end ajax

    $(this).bind('click', function() {
    // bind stuff

    }); // end bind

}); // end one

顺便说一下,你熟悉 load() 方法?我发现基本的ajax更容易(因为它作用于包装的集合,而不是像 $。ajax()这样的独立函数。这里是我将如何重写这个 load()

by the way, are you familiar with the load() method? i find it easier for basic ajax (as it acts on the wrapped set, instead of it being a standalone function like $.ajax(). here's how i would rewrite this using load():

$('.classSelect').one('click', function() {
    var options = {
       type : 'post',
       dataType : 'text',
       data : {
         '_service' : myService,
         '_program' : myProgram ,
         'param' : myParams
       }           
    } // end options

    // load() will automatically load your .classSelect with the results
    $(this).load(myUrl, options);


    $(this).click(function() {
    // etc...

    }); // end click

}); // end one