(☞ຈل͜ຈ)☞ Главная  Статьи  Загрузчик Домой

Ok!
Ok!
169
/* javascript url кодирует сорсы всех картинок */
    var arr = document.querySelectorAll('img')

    arr.forEach(function(item, i, arr) {
        var uri = arr[i].src;
        var encoded = encodeURI(uri);
        arr[i].src = encoded;
    });
urlencode, имена картинок10090url кодировать все файлы картинок javascript
146
<?if($r['Stats']['ReviewsTotalCount'] > 10){?>
<div class="pagination">
<ul>
<?$tot = $r['Stats']['ReviewsTotalCount'];
$page = htmlspecialchars($_REQUEST['page'],3) ;
$pes = ceil($tot / 10);
for($p=1; $p<=$pes; $p++){?>
<li class="<?=($p==$page)?'active':''?>"><a href="/otzyvy/?page=<?=$p?>" rel="nofollow"><?=$p?></a></li>
<?}?>
</ul>
</div>
<?}?>
пагинация, pagination, php10290Php скрипт пагинации
67
<? $APPLICATION->AddHeadString('ваш_код',true); ?>
шапка, битрикс, head10900Добавить любую строку в шапку Битрикс
152
$('[name=docviewer]').show(200, function(){$(document).on('click', function(e){
                    $("#docviewer").hide()
                })});
iframe close, закрыть iframe10900После показа iframe закрыть его по щелчку снаружи
157
<?$name = substr($arItem['PREVIEW_TEXT'], strpos($arItem['PREVIEW_TEXT'], "<b>") + 3, strpos($arItem['PREVIEW_TEXT'], "</b>") - strpos($arItem['PREVIEW_TEXT'], "<b>") - 3)?>
substr10900Часть строки между символами <b> и </b>
161
function price($path, $part){
    $file = fopen($path, "r");
    $text = fread($file, filesize($path));
    $lines = explode(PHP_EOL, $text);
    $v = false;
    $str = "<table>";
    foreach ($lines as $i=>$line) {
        if (strpos($line, $part)) {
            $v = true;
            continue;
        }
        if(strpos($line, ";") > 2 && $v == true){
            $l = explode(";", $line);
            $str .= "<tr><td>" . $l[0] . "</td><td>" . $l[1] . "</td></tr>";
        }
        if(strpos($line, ";") === false && $v == true){
            $str .= "<tr><th colspan='2'>" . $line . "</th></tr>";
        }
        if (strpos(" ".$line, ";;") > 0 && $v == true) {
            $v = false;
            break;
        }
    }
    $str .= "</table>";
    return $str;
}
прайс, price, функция прайс10900Функция постройки прайса таблицы по текстовой таблице в файле
204
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "foo");
});

Promise.all([p1, p2, p3]).then(values => {
  console.log(values);
});
Promise, JS10900Промис яваскрипт
158
RewriteRule ^receipt/(.+)/$ receipt/full.php?tag=$1 [L]
редирект, строка на папку10970Перевод в htaccess с get параметра на папку и садресом
242
use BitrixMainPageAsset;
use BitrixMainPageAssetLocation;
Asset::getInstance()->addString("<script>***</script>", true, AssetLocation::AFTER_JS);
// AssetLocation::BEFORE_CSS;
// AssetLocation::AFTER_CSS;
// AssetLocation::AFTER_JS_KERNEL
// AssetLocation::AFTER_JS
head, js, css, d710980Вставка ссылок в head Битрикс
170
/bitrix/admin/perfmon_table.php?PAGEN_1=1&SIZEN_1=20&lang=ru&table_name=b_event&by=DATE_INSERT&order=desc
битрикс, отправленные письма11020Список отправленных писем в Битрикс
214
[display-posts category="apartamenty" image_size="medium" include_excerpt="true" orderby="date" order="ASC" include_excerpt_dash="false"]
список записей, WP11090Плагин WP – Display Posts для вывода списка записей по критериям
71
function resi($src,$w,$h)
{
    $im_array = explode('/', $src);
    $folder = "/" . $im_array[1] . "/" . $im_array[2] . "/";
    $file = end($im_array);
    $root_path = "/home/d/dlmlru/shop_beta/public_html";

    if(!is_file( $root_path . "/images/products/" . 'N_'. $file)) {
        $inFile = $root_path . $src;
        $outFile = $folder . 'N_' . $file;
        $image = new Imagick($inFile);
        $image->thumbnailImage($w, $h);
        $image->writeImage($root_path . $outFile);
        return $folder . 'N_' . $file;
    }else{
        return $folder . 'N_' . $file;
    }
}


# example <img src="<?echo resi('/images/products/DSC08794_КМГ613_1600.jpg', 200, 133);?>" width="200"/>
resize, php12000Ресайз картинок php
199
function maskPhone(selector, masked = '+7 (___) ___-__-__') {
        const elems = document.querySelectorAll(selector);

        function mask(event) {
            const keyCode = event.keyCode;
            const template = masked,
                def = template.replace(/D/g, ""),
                val = this.value.replace(/D/g, "");

            let i = 0,
                newValue = template.replace(/[_d]/g, function (a) {
                    return i < val.length ? val.charAt(i++) || def.charAt(i) : a;
                });
            i = newValue.indexOf("_");
            if (i !== -1) {
                newValue = newValue.slice(0, i);
            }
            let reg = template.substr(0, this.value.length).replace(/_+/g,
                function (a) {
                    return "\d{1," + a.length + "}";
                }).replace(/[+()]/g, "\$&");
            reg = new RegExp("^" + reg + "$");
            if (!reg.test(this.value) || this.value.length < 5 || keyCode > 47 && keyCode < 58) {
                this.value = newValue;
            }
            if (event.type === "blur" && this.value.length < 5) {
                this.value = "";
            }

        }

        for (const elem of elems) {
            elem.addEventListener("input", mask);
            elem.addEventListener("focus", mask);
            elem.addEventListener("blur", mask);
        }

    }
    maskPhone('input[type=tel]');
маска телефона12009Скрипт JS маски телефона
195
include_once($root . 'getID3/getid3/getid3.php');
    $getID3 = new getID3;
    $file = $getID3->analyze($root . $file_src);

    #echo("Duration: ".$file['playtime_string'].
    #" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
    #" / Filesize: ".$file['filesize']." bytes<br />");
gd3, анализ видео12010Анализ длительности, ширины, высоты видео
201
function send(onError, onSuccess, url, method = 'GET', data = null, headers = [], timeout = 60000) {
  let xhr;

  if (window.XMLHttpRequest) {
      // Chrome, Mozilla, Opera, Safari
      xhr = new XMLHttpRequest();
  }  else if (window.ActiveXObject) { 
      // Internet Explorer
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhr.open(method, url, true);


  headers.forEach((header) => {
      xhr.setRequestHeader(header.key, header.value);
  })
  

  xhr.timeout = timeout;

  xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
      if(xhr.status >= 400) {
          onError(xhr.statusText)
      } else {
          onSuccess(xhr.responseText)
      }
      }
  }

  xhr.send(data);
}
xhr, request, XMLHttpRequest, JS12090XMLHttpRequest обернутый в функцию
205
function flog($fname, $ftext, $write_a_w_state = null){
    if(!$write_a_w_state)
        $write_a_w_state = "a+";
    $fp = fopen("/home/d/dlmlru/posuda/public_html/log/" . $fname, $write_a_w_state);
    fwrite($fp, date("Y-m-d H:i:s ") . $ftext . "

");
    fclose($fp);
}
flog12090функция логирования php
222
echo <<<EOH
 ----------   ----------- -- ----------
 результат      значение      оп тест
 ----------   ----------- -- ----------
EOH;
eoh, php print formated12090Форматированная строка в PHP
171
http://example.com/?_ym_debug=1
метрика, counter test, проверка12300Проверка счетчиков и событий метрики в консоли
174
function find_closed() {
    //clearTimeout(typingTimer);
    //typingTimer = setTimeout(doneTyping, doneTypingInterval);
    var found;
    var tr = jQuery('.pricing tr');
    var pos = jQuery('body, html').scrollTop();
    var s = jQuery('#searchfield').val();
    //var add = jQuery('.prices').first().position().top;
    var old, i, cont;
    if(s.length > 2) {
        old = jQuery('.found_color').parents('td');
        jQuery.each(old, function(){
            cont = jQuery(this).text();
            old.text(cont);
        });
        jQuery('tr').removeClass('found');
        for (i = 0; i < tr.length; i++) {

            if (tr.eq(i).text().toLowerCase().indexOf(s.toLowerCase()) > -1) {
                tr.eq(i).addClass('opened found');
                var text = tr.eq(i).children('td:first-child').text().replace(s, '<span class=found_color>' + s + '</span>');
                //console.log(text);
                tr.eq(i).children('td:first-child').html(text);
                found = 1;
            }else{
                //tr.eq(i).remove();
                tr.eq(i).removeClass('opened');
                tr.eq(i).removeClass('found');
            }

        }
        if(jQuery('.found').length){
            var E = setTimeout(function(){
                pos += jQuery('.found').first().parents('table').position().top;
                jQuery('body, html').animate({scrollTop: pos}, 300, 'swing');
                console.log(pos);
            },300);
        }
        if (found < 1) {
            jQuery('.not-found').text('Не найдено на этой странице. Поищите через общий поиск')
        }
    }
}
найти в скрытом аккордионе12300find_closed с подстветкой
203
/^([a-z0-9_.-]+)@([a-z0-9_.-]+).([a-z.]{2,6})$/
regexp, email. JS14800Регулярное выражение для проверки email
1 2 3 4 5 6 7 8 9 10 11 12 13 14