JavaScript: отслеживание клика вне элемента

Задача: отследить клик вне элемента div.

Решение: для этого навесим событие на клик вышестоящего элемента, и при клике анализируем, то на чём кликнули «внутри» или «снаружи»:

Например:

html:

<div class="el1">
   <div class="el2"></div>
   <div class="el3"></div>
   <div class="el4"></div>
   <div class="el5"></div>



</div>

javascript:

$(".el1" ).bind( "click", function(e) {
                        if ( $(e.target).closest('.el4').length ) {
                            console.log("внутри");
                        return;
                        };
                        console.log("снаружи");  
                   });

Datatables.net: субгриды для таблицы

Задача: при щелчке по одной из ячеек, разворачивать «subgrid» для таблицы. Примерно так:

Решение:

<table id="ownersgrid" class="display" style="width:100%">
        <thead>
            <tr>                
                <th>#</th>
                <th></th>
                <th>Наименование</th>
                <th>Полное наименование</th>
                <th>Телефон</th>    
                <th>Email</th> 
                <th>Договора</th>
            </tr>
        </thead>
</table>

<script>
 ownerstable=$('#ownersgrid').DataTable( {
        dom: 'frtipB',
        destroy: true,
        select: true,
        lengthMenu: [
            [ 10, 25, 50, -1 ],
            [ '10 строк', '25 строк', '50 строк', 'Все строки' ]
        ],
        buttons: [            
            {
            text: 'Редактировать',
                action: function ( e, dt, node, config ) {
                  ConnectorEdit("edit");  
                }
            },
            {
            text: 'Добавить',
                action: function ( e, dt, node, config ) {
                  ConnectorEdit("add");  
                }
            },
            
            'excel','print','pageLength',
        ],        
         paging: true,
         keys: true,
         //scrollY:        400,
        //scrollCollapse: true,
        //scroller:       true,         
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "/server/owners/OwnersGrid",
            "type": "POST",
            "data": {               
            }
        },
    "language": {
             url: '/js/i18n/datatable.json'
        },        
    "columns": [                    
            { "data": "id"},
            { "data": "deleted" },
            { "data": "name"},
            { "data": "full_name" },
            { "data": "phone" },
            { "data": "email" },
            { className: 'dt-control',orderable: false,data: null,defaultContent: '',width: '10%'},
        ]        
    } );
    $('#ownersgrid').unbind();
    $('#ownersgrid').on('dblclick', 'tbody td', function () {        
         OwnerEdit("edit");
    }); 
    $('#ownersgrid tbody').on('click', 'td.dt-control', function () {
        var tr = $(this).closest('tr');
        var row = ownerstable.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            destroyChild(row);
            tr.removeClass('shown');
        }
        else {
            // Open this row
            createChild(row);
            tr.addClass('shown');
        }
    } );    
function createChild ( row ) {
    // This is the table we'll convert into a DataTable
    var table = $('<table class="display" style="width:100%">'+
        '<thead>'+
        '    <tr>                '+
        '        <th>#</th>'+
        '        <th></th>'+
        '        <th>Наименование</th>'+
        '        <th>Полное наименование</th>'+
        '        <th>Телефон</th>    '+
        '        <th>Email</th> '+
        '        <th>Договора</th>'+
        '    </tr>'+
       ' </thead>'+
    '</table>');


    // Display it the child row
    row.child( table ).show();
 
    // Initialise as a DataTable
    var usersTable = table.DataTable( {
       dom: 't',
        destroy: true,
        select: true,
        lengthMenu: [
            [ 10, 25, 50, -1 ],
            [ '10 строк', '25 строк', '50 строк', 'Все строки' ]
        ],
        buttons: [            
            {
            text: 'Редактировать',
                action: function ( e, dt, node, config ) {
                  ConnectorEdit("edit");  
                }
            },
            {
            text: 'Добавить',
                action: function ( e, dt, node, config ) {
                  ConnectorEdit("add");  
                }
            },
            
            'excel','print','pageLength',
        ],        
         paging: true,
         keys: true,
         //scrollY:        400,
        //scrollCollapse: true,
        //scroller:       true,         
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "/server/owners/OwnersGrid",
            "type": "POST",
            "data": {               
            }
        },
    "language": {
             url: '/js/i18n/datatable.json'
        },        
    "columns": [                    
            { "data": "id"},
            { "data": "deleted" },
            { "data": "name"},
            { "data": "full_name" },
            { "data": "phone" },
            { "data": "email" },
            { className: 'dt-control',orderable: false,data: null,defaultContent: '',width: '10%'},
        ]        
    } );
};
function destroyChild(row) {
    var table = $("table", row.child());
    table.detach();
    table.DataTable().destroy();
 
    // And then hide the row
    row.child.hide();
}
</script>

Битрикс: Вывод файла в детальном отображении товара

Задача: 1) позволять прикреплять инструкцию к товару. 2) Отображать её в товаре, в том случае если файл прикреплен.

Решение:

  1. Добавляем руками новое свойство в информационном блоке «Основной каталог товаров»

2) Открываем шаблон детального отображения товара и добавляем:

В начале файла, заполняем переменную $INCTRUCTION_SRC

<?		
$res = CIBlockElement::GetProperty($arResult['IBLOCK_ID'], $arResult['ID'], "sort", "asc", array("CODE" => "files"));
if ($ob = $res->GetNext())
    {			
$INSTRUCTION_VALUE = $ob['VALUE'];
$file = CFile::GetFileArray($INSTRUCTION_VALUE);
$INSTRUCTION_SRC = $file['SRC'];
    }
?>

В нужном месте для вывода добавляем:

<?php
 if ($INSTRUCTION_SRC!=""){
?>
<a href="<?=$INSTRUCTION_SRC;?>">Инструкция</a>
<?php
};
?>

Результат:

datatables.net: перекашивает заголовок таблицы при переключении между вкладками

При переключении между вкладками, иногда шапка таблицы «узежает».

Решение: в момент переключения вкладок, «перерисовываем» шапку:

    $("#tabs").tabs({
	activate: function( event, ui ) { 
		$('#client_pays_grid').dataTable().fnAdjustColumnSizing();
   });

Дошли руки до datatables.net

Наконец дошли руки до освоения плагина databales.net для работы с таблицами. До этого всё использовал jqgrid. Вот типичный шаблон c выгрузкой в excel, загрузкой данных из json, добавления в POST своих данных, получения id выделенной строки.

HTML:

<table id="clientsgrid" class="display" style="width:100%">
        <thead>
            <tr>
                <th>#</th>
                <th></th>
                <th>Телефон</th>
                <th>ФИО</th>
                <th>Email</th>
                <th>Дата</th>
            </tr>
        </thead>
    </table>

Javascript:

 function ClientsGridList(){

    table=$('#clientsgrid').DataTable( {
        dom: 'Bfrtip',
        destroy: true,
        select: true,
        buttons: [
            'excel','print'
        ],        
         paging: true,
         keys: true,
        //scrollY:        200,
        //scrollCollapse: true,
        //scroller:       true,         
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "/server/clients/ClientsGrid",
            "type": "POST",
            "data": {
                "owner":owner_select.value,
                "segment":users_groups_array_select.value
            }
        },
    "language": {
             url: '/js/i18n/datatable.json'
        },        
    "columns": [
            { "data": "id"},
            { "data": "deleted" },
            { "data": "phone"},
            { "data": "name" },
            { "data": "email" },
            { "data": "dt"}            
        ]        
    } );
    $('#clientsgrid').unbind();
    $('#clientsgrid').on('dblclick', 'tbody td', function () {
         tr = $(this).closest('tr');
         //console.log(tr);
         row = table.row( tr );
         data=row.data();
         user_id=data.id;         
         DrawCartUser(user_id);
    }); 
   // table.ajax.reload();
  };    

PHP:

$owner= _POST("owner"); // владелец (если суперадмин - выводим всех)
$segment= _POST("segment"); // какой сегмент (если -1, выводим всех)
$draw= _POST("draw"); // какая страница
$start= _POST("start"); // с какой записи по счету
$length= _POST("length"); // записей на страницу
$order= _POST("order")[0]["column"]; // по какой колонке сортируем
$order= _POST("columns")[$order]["data"];
$sidx= _POST("order")[0]["dir"]; // способ сортировки
$search_value=_POST("search")["value"]; // что ищем
$search_regex=_POST("search")["regex"]; // регулярка

$res=$Users->GetClientsGrid($Users,$owner,$segment,$start,$length,$order,$sidx,$search_value);    
if ($res->error):
        echo '{"error": "'.$res->errortext.'" }';
        die();
   else:
        $res->result->draw=$draw;
        jsonExit($res->result);
endif;

Ну и получается что то вроде:

1 14 15 16 17 18 55