JavascriptとjQueryバイク

同僚のコードを再び開いて恐ろしいことに、私はこの記事を書くことにしました。 同時に誰かにとっても役に立つことを願っていますし、初心者にとっては、この記事へのリンクを投げることで、コードの何が問題なのかを説明しやすくなります。

もちろん、そのようなものの数は非常に多いので、この記事では私はごく少数に制限します。



1.コード内の定数



この問題は、javascriptだけでなく、全体としてのプログラミングにも関係しています。 例を考えてみましょう:

$elem.on('keydown', function(e) {
    if (e.keyCode == 27) {
        //...
    }
});
      
      





27? , — ESC. , , , , , .

, ESC, , , KEY_ESC = 27



2.



(, , ..), - . (, ajax). :



var id = $(this).attr('id').substring(8);
      
      





— 8. html ..

( ):



var last_id = $('#answer_pid' + id + ' li:first div').attr('id').substr(7);
      
      





, js .



:

<div class="comment" id="comment_123"></div>
      
      





var id = $(this).attr('id').substring("comment_".length);
      
      





( ), js html.



data-* ,

<div class="comment" data-id="123"></div>
      
      





:

var id = $(this).attr('data-id');
      
      







var id = $(this).data('id');
      
      





( attr data )



3. $.post



— jquery ajax — $.ajax. shorthand , $.get, $.load, $.post .. , ( , json, post ), $.ajax.

shorthand , :



:



1.

$.post(url, data, function(data) {
            data = $.parseJSON(data);
            //...
});

      
      





2. try catch

$.post(url, data, function(data) {
	    try {
                data = $.parseJSON(data);
            } catch (e) {
                return;
            }
            //...
});

      
      





3. , $.post dataType ( , success ).


$.post(url, data, function(data) {
    //...
}, 'json');

      
      







. - , 5 , , .

$.post , :

$.post(url, data, function(data) {
    //...
}, 'json').error(function() {
   ///
});
      
      







— . — , ajax , :


$.ajaxSetup({
    error: function() {
        //   ,   
    }
});

      
      







$.post. — $.post ( dataType ). $.ajax. .


$.ajax({
    type: "POST"
    url: url,
    data: data,
    dataType: "json",
    success: function(data) {
        //
    },
    error: function() {
        //
    }
});

      
      







4.



(, « »). :


$('.comment a.delete').click(function(){
    //
});

      
      







— ( ). , ( ):


$('.comment a.delete').unbind('click').click(function() {
    //
});

      
      





: jQuery 1.7 on, , .

:

$('body').on('click', 'a.external', function(e) {
	//          external
});

      
      





, .

, . :


$('body').on('mousemove', selector, function() {
	//
});

      
      







5. Namespaced events



, namespaced events jQuery 1.2 — ( ).

:


$('a').on('click', function() {
	// 1
});
$('a').on('click', function() {
	// 2
});

      
      





, . — $('a').off('click') . namespaced events. :


$('a').on('click.namespace1', function() {
	// 1
});
$('a').on('click.namespace2', function() {
	// 2
});

      
      





$('a').off('click.namespace2');

namespaced events : docs.jquery.com/Namespaced_Events





, . .



All Articles