开发者

difference between this and $(this) [duplicate]

开发者 https://www.devze.com 2023-01-16 08:46 出处:网络
This question already has answers here: 开发者_C百科 Closed 12 years ago. Possible Duplicate: jQuery $(this) vs this
This question already has answers here: 开发者_C百科 Closed 12 years ago.

Possible Duplicate:

jQuery $(this) vs this

When using jQuery, whats the difference between this and $(this)?


this is to call DOM methods.
$(this) is to call jQuery methods.


Generally, use $(this) when you're going to follow it up with another jquery function for a wrapped set. Use this when you're trying to access an element (such as .name) from the DOM.

An example of some code I have that adds another row to a table, based on a model row that is somewhere else, hidden in the form and not visible. The code below uses both $(this) and this, in different contexts.

    {% 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();
        }); 
    }  


$(this) is the context of the element you are working on or the one that get the event.

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

in the above the $(this) referes to the element that has an id of MyElement and that was clicked on.

this is simply the normal javascript object.

0

精彩评论

暂无评论...
验证码 换一张
取 消