代码之家  ›  专栏  ›  技术社区  ›  Tyler Gillies

此和$(此)[副本]之间的差额

  •  0
  • Tyler Gillies  · 技术社区  · 14 年前


    jQuery $(this) vs this

    使用jQuery时,this和$(this)有什么区别?

    3 回复  |  直到 8 年前
        1
  •  0
  •   Unoti    14 年前

    通常,当您要使用另一个jquery函数来处理包装集时,请使用$(this)。当您试图从DOM访问元素(如.name)时,请使用此选项。

    我的一些代码的一个例子,它基于一个隐藏在表单中且不可见的模型行,将另一行添加到表中。下面的代码在不同的上下文中同时使用$(this)和this。

        {% comment %}
            llforms_add_row('ir'): used to add a new row on a repeating form.
            if rowtype is 'ir', looks for a <div id="ir_row_blankform"> and copies it
            to the end of <div id="ir_rows">.
        {% endcomment %}
        function llforms_add_row(row_type) {
            var new_row=$('#'+row_type+'_row_blankform').clone();
            var rows_tag='#'+row_type+'_rows';
            {# find the highest row number in use #}
            var highest=1;
            $(rows_tag).children().each(function(n){
                var seq=$(this).attr('rownum')*1;
                if (seq > highest) highest=seq;
            }); 
            highest += 1;
    
            {# massage the new row into what we need #}
            var new_id=highest.toString();{# Just the numeric part of the id #}
            var new_row_id=row_type+'_row_'+new_id;{# The full DOM id #}
            new_row.attr('style',"display:none");{# We will fade it in, so start it invisible #}
            new_row.attr('id',new_row_id);
            new_row.attr('rownum',new_id);
            $('input', new_row).each(function(n){
                this.name=this.name.substring(0,this.name.length-9)+new_id;
                this.id=this.name;
            }); 
            $('a', new_row).each(function(n) {
                this.href=this.href.replace('blankform',new_id);
            }); 
            new_row.appendTo(rows_tag);
            $('#'+new_row_id).slideDown('fast',function(){
                $('input:first', new_row).focus();
            }); 
        }  
    
        2
  •  1
  •   Naveed    14 年前

    this 是调用DOM方法。
    $(this)

        3
  •  -1
  •   griegs    14 年前

    $(this) 是您正在处理的元素的上下文或获取事件的元素的上下文。

    $('#MyElement').click(function(){ $(this).doSomething })
    

    在上面 引用id为的元素 MyElement 点击了。

    this 只是普通的javascript对象。