регулярные выражения
почитать можно тут.
1 2 3 4 5 6 7 8 9 10 |
//нужно получить все ссылки на изображения var str=page.content; var regexp=/<img[^<>]*?src[^<>]*?=[^<>]*?"([^<>]*?)"[^<>]*?>/g; var r; console.log("tyt"); links=[]; for(var i=0;r=regexp.exec(str);i++){ console.log("i="+i+" "+r[1]); links[i]=r[1]; } |
Здорова ребятки! Немножно разберем синтаксис языка javascript
Подключение файлов Javascript в Drupal 7
Создание и подключение кода:
в Javascritp файлы в html документ подключаются следующим образом
1 2 3 |
<head> <script type="text/javascript" src="js/jquery.js"></script> </head> |
Добавляется между тегов <head></head>, src указывает на путь к файлу
Можно так же использовать код непосредственно внутри самого html файла, для этого просто прописываем код внутри файл, например выведем в цикле от 1 до 9 числа, для этого мы добавим следующий код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> var a=1; for(i=1;i<10;i++) document.write(i+"<br>"); </script> <style type="text/css"> #blog {border:1px solid #aaf;background:#f9f9f9;padding:4px} .post {border:1px solid #aaa;background:#fff;padding:4px;margin: 2px 0} #loading {height: 40px} </style> </head> <body> <h1>Hellow world!</h1> </body> </html> |
и получим в вывод на экран
Знак $ что означает в Javascritp и в Jquery
Знак $ что означает в Javascript »
Это символом можно просто функцию назвать:
1 2 3 4 5 6 7 8 |
var a=10; function $(data) { for(i=0;i<data;i++) document.write(i+"<br>"); } $(a);//вызов функции $ |
Вывод на экран:
Можно как имя переменной использовать
1 2 3 |
var $a=10; document.write($a);//выведет 10 |
Выведется 10 на экран.
так же доллар может при использовании jquery означать что это jquery, типо короткая запись вместо Jquery() мы вызываем $() как бы так.
Функция jQuery.getJSON ($.getJSON)
Разберем немножно эту функцию, она принимает 3 параметра, первый это путь к обработчику либо урл, второй параметр — это передаваемые данные, у нас получается эти данные передаются методом GET мы получаем их в файле и третий параметр это функция в которую попадают полученные данные, то есть те данные которые уже назад передаются скрипту, вот код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> var $a=10; // document.write($a);//выведет 10 //сразу идет вызов функции //первый параметр скрипт обработчик, второй передаваемые данные //а третий вызываемая функция в которую передаются полученные данные $.getJSON('getposts.php', {count:0, last:5}, function(data){//третий параметр функция которая принимает полученые от скрипта данные document.write(data.length); if (data.length > 0) { //выведем полученые данные for(i=0;i<data.length;i++) { document.write(data[i].title+" "+data[i].posted_at+" "+data[i].comments_count+ " "+data[i].content+" "+data[i].id+"\n<br>"); } } } ); </script> </head> <body> <h1>Hellow world!</h1> </body> </html> |
Файл обработчик
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php if(isset($_GET['count'])&&isset($_GET['last'])) { $json = json_decode($_GET['count'], true); file_put_contents("data.txt",$json ); $json1 = json_decode($_GET['last'], true); file_put_contents("data1.txt",$json1); $arr = array(0 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 1 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 2 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 3 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 4 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 5 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5))); Sleep(2);//задержка в 3 секунды // $arr=array();//прекращает загрузку file_put_contents("data2.txt",count($arr)); echo json_encode($arr); } ?> |
Мы передаем вторым параметром в $.getJSON функции два значения: count и last и их получаем в файле обработчике getposts.php методом get.
На экран скрипт выведет у нас через время как подгрузит то получим следующий вывод, сначала будет надпись hellow world, а затем когда подгрузит функция jQuery.getJSON данные и начнет их выводит то совсем другой вывод получается надпись «hellow world» пропадает и появляется следующий вывод:
Мы взяли и получили данные из файла с помощью функции $.getJSON в наш скрипт, а теперь давайте подумаем как же нам сделать чтобы эти данные вывелись в какой то блок?
Вывод полученых данных через $.getJSON в блок
Создаем блок и используем функцию append()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> var $a=10; // document.write($a);//выведет 10 //сразу идет вызов функции //первый параметр скрипт обработчик, второй передаваемые данные //а третий вызываемая функция в которую передаются полученные данные $.getJSON('getposts.php', {count:0, last:5}, function(data){//третий параметр функция которая принимает полученые от скрипта данные if (data.length > 0) { //выведем полученые данные for(i=0;i<data.length;i++) { //добавляем данные к элементу с идентификатором id=images $('#images').append(data[i].title+" "+data[i].posted_at+" "+data[i].comments_count+ " "+data[i].content+" "+data[i].id+"\n<br>"); } } } ); </script> </head> <body> <h1>Hellow world!</h1> <div id="images"> </div> </body> </html> |
мы добавили в коде выше контейнер с идентификатором id=»images»
1 2 |
<div id="images"> </div> |
в этот контейнер типо добавляются данные
и сам обработчик смотрим который возвращает нам данные
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php if(isset($_GET['count'])&&isset($_GET['last'])) { $json = json_decode($_GET['count'], true); file_put_contents("data.txt",$json ); $json1 = json_decode($_GET['last'], true); file_put_contents("data1.txt",$json1); $arr = array(0 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 1 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 2 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 3 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 4 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 5 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5))); Sleep(2);//задержка в 3 секунды // $arr=array();//прекращает загрузку file_put_contents("data2.txt",count($arr)); echo json_encode($arr); } ?> |
вывод:
ну в общем вывели на экран.
Бесконечная прокрутка на jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/endless.js"></script> <style type="text/css"> #blog {border:1px solid #aaf;background:#f9f9f9;padding:4px} .post {border:1px solid #aaa;background:#fff;padding:4px;margin: 2px 0} #loading {height: 40px} </style> </head> <body id="hello_body"> <div id="blog"> <div id="loading" style="display:none">Loading....</div> </div> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
// script for endless scrolling using jQuery // demo: http://www.jstoolbox.com/demo/endless/ var engine = { posts : [],//массив с постами target : null,//куда нужно вставлять идентификатор тека id busy : false,//состояние скрипта count : 5,//количество записей которые получат в массив render : function(obj){ var xhtml = '<div class="post" id=post_'+obj.id+'>'; if (obj.title) { xhtml += '<h2>'+obj.title+'</h2>'; } if (obj.posted_at) { xhtml += '<div class="posted_at">Posted on: '+obj.posted_at+'</div>'; } if (obj.comments_count) { xhtml += '<div class="comments_count">Comments: ' + obj.comments_count + '</div>'; } xhtml += '<div class="content">' + obj.content + '</div>'; xhtml += '</div>'; return xhtml; }, init : function(posts, target){ if (!target) return; this.target = $(target); this.append(posts); var that = this; $(window).scroll(function(){ if ($(document).height() - $(window).height() <= $(window).scrollTop() + 50) { that.scrollPosition = $(window).scrollTop(); that.get(); } }); }, append : function(posts){ posts = (posts instanceof Array) ? posts : []; this.posts = this.posts.concat(posts); for (var i=0, len = posts.length; i<len; i++) { this.target.append(this.render(posts[i]));//фукнция добавляет к елементу данные target содержит идентификатор id блока div } if (this.scrollPosition !== undefined && this.scrollPosition !== null) { $(window).scrollTop(this.scrollPosition); } }, get : function() { if (!this.target || this.busy) return; if (this.posts && this.posts.length) { var lastId = this.posts[this.posts.length-1].id; } else { var lastId = 0; } this.setBusy(true);//показывает Loading var that = this; $.getJSON('getposts.php', {count:this.count, last:lastId}, function(data){ if (data.length > 0) { that.append(data); } that.setBusy(false);//скрывает Loading } ); }, showLoading : function(bState){//показывает загружать или нет var loading = $('#loading'); if (bState) { $(this.target).append(loading); loading.show('slow'); } else { $('#loading').hide(); } }, setBusy : function(bState){ this.showLoading(this.busy = bState); } }; // usage $(document).ready(function(){ engine.init(null, $("#blog"));//инициализация engine.get();//функция которая делает getJSON запрос }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php if(isset($_GET['count'])&&isset($_GET['last'])) { $json = json_decode($_GET['count'], true); file_put_contents("data.txt",$json ); $json1 = json_decode($_GET['last'], true); file_put_contents("data1.txt",$json1); $arr = array(0 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 1 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 2 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 3 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 4 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5)), 5 => array("title" => статья, "posted_at" => текст,"comments_count"=>40,"content"=>"контент","id"=>($_GET['last']+5))); Sleep(2);//задержка в 3 секунды // $arr=array();//прекращает загрузку file_put_contents("data2.txt",count($arr)); echo json_encode($arr); } ?> |
вывод:
Скрипт работает, когда ползунок прокрутки страницы доходит вниз то у нас делается запрос и подгружается новые страницы. короче такой типо скрипт. Нихочу расписывать что и как, смотрите по коду все.
Javascript получение переменных в функцию из <input> и <div>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Событие onclick</title> <script> function fun() { //получаем значение переменной из div var data = document.getElementById('d').innerHTML.toUpperCase(); //получаем значение переменной из input var data2= document.getElementById('d2').value.toUpperCase(); if(data2!=data) alert("Ошибка! Неправильный символ"); else alert("Правило! Правильный символ"); // document.forms.myform.submit(); /* if(data.toUpperCase()==data2.toUpperCase()) document.forms.myform.submit(); else alert("Ошибка ! Неправельный символ."); */ } </script> </head> <body> <form action="" id="myform" method="post" name="myform"> <p>Введите адрес электронной почты и нажмите кнопку «Проверить»</p> <p><input placeholder="E-mail" type="text" id="d2"> <span id="status"></span></p> <p><input type="submit" value="Проверить" onclick="fun()" name="kkk"></p> <div id="d">k</div> </form> </body> </html> <?php if(isset($_POST['kkk'])) { echo "<pre>"; print_r($_POST); echo "</pre>"; } ?> |
JavaScript — получение данных из блока класса и замена на другие данные
Задание нужно взять из блока номер телефона и заменить его на два номера если он совпадет с одним из четырех номеров. Задание простое, сразу вот код:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript" src="http://test_ftp1/sites/all/themes/starfish_responsive_theme/js/jquery.js"></script> <script type="text/javascript"> //функция ready будет выполнена после загрузки документа $(document).ready(function(){ var data=$("span.phone_alloka").html();//считываем переменную из блока с классом .phone_alloka alert(data);//выведем что вышло //document.write(data); /* Фед.номер 7923775 58 98 Гор. Номер 8-383-375-58-98 Фед.номер 7923775 34 14 Гор. Номер 8-383-375-34-14 Фед.номер 7923775 34 84 Гор. Номер 8-383-375-34-84 Фед.номер 7923775 38 68 Гор. Номер 8-383-375-38-68*/ if(data=="+7 (923) 775-38-68") { alert("1 '"+data+"'"); //выводим во все блоки span с классом phone_alloka данные в формате html $("span.phone_alloka").html("+7 (923) 775-38-68, 8-383-375-38-68<br>"); } else if(data=="+7 (923) 775-34-14") { alert("2 '"+data+"'"); //выводим во все блоки span с классом phone_alloka данные в формате html $("span.phone_alloka").html("+7 (923) 775-34-14, 8-383-375-34-14<br>"); } else if(data=="+7 (923) 775-34-84") { alert("3 '"+data+"'"); //выводим во все блоки span с классом phone_alloka данные в формате html $("span.phone_alloka").html("+7 (923) 775-34-84, 8-383-375-34-84<br>"); } else if(data=="+7 (923) 775-58-98") { alert("4 '"+data+"'"); //выводим во все блоки span с классом phone_alloka данные в формате html $("span.phone_alloka").html("+7 (923) 775-58-98, 8-383-375-58-98<br>"); } }); </script> </head> <body id="hello_body"> <div id="k" class="phone_alloka">hell</div> <span data-phone="%20%20+7%28383%29-3-02-02-02%20" class="phone_alloka">+7 (923) 775-38-68</span> <span data-phone="%20%20+7%28383%29-3-02-02-02%20" class="phone_alloka">+7 (923) 775-38-68</span> <span data-phone="%20%20+7%28383%29-3-02-02-02%20" class="phone_alloka">+7 (923) 775-38-68</span> </body> </html> |
С помощью
1 |
var data=$("span.phone_alloka").html(); |
мы считываем данные в переменную дата наверное из первого блока span с классом phone_alloka, а с помощью
1 |
$("span.phone_alloka").html("+7 (923) 775-38-68, 8-383-375-38-68<br>"); |
выводим во все блоки span с классом phone_alloka.
Так же можно вывести текст во все блоки используя функцию text() вместо html()
1 |
var data=$("span.phone_alloka").text(); |
код выше добавит в переменную data данные в виде текста со всех блоков span с классом phone_alloka, если мы применим к коду в самом верху и заменим html на text то появится в переменной data 3 номера телефонов, все в одну скинит
1 |
$("span.phone_alloka").text("+7 (923) 775-38-68, 8-383-375-38-68<br>"); |
А этот код выведет не html текст во все span с классом alloka, а просто текст, все теги html заменятся в html сущьностями, просто теги выведутся.
JavaScript бегущая строка
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<html> <head> <link href="css/style.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> var timerID2=setInterval(function(){ var data=$("#interest").text(); re=/(.*?)\/.*/i;//экранирование символов \ var found=data.match(re);//возвращается в виде массивов var persent=found[1].trim(); persent++; drow_line(persent); },100); function drow_line(persent)//500 пиксселей это полная ширина картинки { if(persent<=100) { //500px - это 100 document.getElementById('interest').innerHTML = persent + '/100'; document.getElementById('progress').style.width = persent * 5 + 'px';//обращаемся к стилю } else { document.getElementById('interest').innerHTML="game over"; } }; </script> </head> <body> <div style="width: 500px; border: 1px solid #666; margin: 0 auto;"> <!-- Выводим проценты --> <center style="color: #666; position: absolute; margin: 15px 0 0 235px;" id="interest"> 0/100 </center> <!-- Выводим полосу прогресса --> <img id="progress" style="width: 0; height: 50px;" src="http://sergey-oganesyan.ru/wp-content/uploads/2014/01/prograss.jpg"> </div> </body> </html> |
Использование JavaScript таймеров
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<html> <head> <script type="text/javascript"> //alert('hellow'); function stop_timer(msg)//остановка таймера { alert(msg); clearTimeout(timer); } function start_timer()//запуск таймера { timer=setInterval(function(){ f(); },2000);//через 2 секунды запускает ф } function f(){ alert('hellow'); setTimeout(stop_timer, 7000,"Привет!");//вызов функции через 2 секунды*/stop_timer(); }; //создаем в глобальной области, запускаем функцию f через каждые 2 секунды var timer=setInterval(function(){ f(); },2000); </script> </head> <body> <p style='background-color:red'>hellow world</p> </body> </html> |
Звук в JavaScript
Запускаем по таймеру звук в javaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<html> <head> <link href="css/style.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> //alert('hellow!'); function f() { var audio = new Audio(); // Создаём новый элемент Audio audio.src = 'notify.ogg'; // Указываем путь к звуку "клика" audio.autoplay = true; // Автоматически запускаем } f(); var timer=setInterval(function(){ f(); }, 2000); </script> </head> <body> </body> </html> |
JavaScript бегущая строка — рулетка iMarque
Простой код, конечно его нужно добарабывать под свои нужды.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<html> <head> <link href="css/style.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> var timerID2=setInterval(function(){ var data=$("#interest").text(); re=/(.*?)\/.*/i;//экранирование символов \ var found=data.match(re);//возвращается в виде массивов var persent=found[1].trim(); persent++; drow_line(persent); },100); function drow_line(persent)//500 пиксселей это полная ширина картинки { if(persent<=100) { //500px - это 100 document.getElementById('interest').innerHTML = persent + '/100'; document.getElementById('progress').style.width = persent * 5 + 'px';//обращаемся к стилю } else { document.getElementById('interest').innerHTML="game over"; } }; </script> </head> <body> <div style="width: 500px; border: 1px solid #666; margin: 0 auto;"> <!-- Выводим проценты --> <center style="color: #666; position: absolute; margin: 15px 0 0 235px;" id="interest"> 0/100 </center> <!-- Выводим полосу прогресса --> <img id="progress" style="width: 0; height: 50px;" src="http://sergey-oganesyan.ru/wp-content/uploads/2014/01/prograss.jpg"> </div> </body> </html> |
JavaScript Ajax Использование аякса по таймеру
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<html> <head> <link href="css/style.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> var i=0; function f1(msg) { i++; var data=i+" - "+msg.data+" - "+msg.name+" - "+msg.fam; $("div#images").prepend(data);//добавляет в начало блока }; function f() { $.ajax({ type: "POST", url: "some.php", data: "name=John&fam=Boston", success: function(msg){ //alert( "Прибыли данные: " + msg ); msg = JSON.parse(msg); f1(msg); } }); }; f();// запуск аякс функции //запуск функции по таймеру var timer=setInterval(function(){ f(); }, 2000); </script> </head> <body> <div id="images" style='border: 2px solid red; width:500px;'> hellow </div> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $result=""; $result['data']= "hellow world!"; if(isset($_POST['name'])) $result['name']=" ".$_POST['name']." "; if(isset($_POST['fam'])) $result['fam']=" ".$_POST['fam']."<br>"; echo json_encode($result); ?> |
JavaScript создание программки для вставки текста, добавления ссылок в блоки и Drag Drop сортировка
Некоторые моменты на которые стоит обратить внимание это от этот код:
1 2 3 4 5 6 7 |
on: { input: function(x) { return function(){ $(c[x]).html(this.value); } }(i) } |
в этом коде on атрибут означает что мы используем типо там находится собития которые будут обрабатыватся, в данном случае мы используем input — это события автозаполенния, типо вводим в поле формы что то и оно в реале изменяется. Тут еще мы могли бы в функции сделать просто c[i], но в данном случае нельзя делать потому что мы используем цыкл и у нас конечное i будет как бы иметь одно значение, поэтому мы используем функцию в функции и ей передаем в качестве параметра (i). Это как бы синтаксис такой в JavaScript
От просто весь код, правда я не закомментировал, разбирайтесь кому нада, если непонятно разбирайтесь пишите вопросы в комментариях 🙂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
<!DOCTYPE HTML> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> #edit > p:after{ content: "Переместить"; margin-left: 10px; } #edit { width: 500px; } #menu a{ margin: 5px; } #block a{ margin: 5px; } .block{ background-color:red; } #content a{ margin: 5px; } </style> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script> $(function() { function ff() { //1 получаем массивы элементов var a=$("#menu a"); var c=$("#content div"); var d=new Array(); //2. обходим элементы в цикле for(i=0;i<c.length;i++) { var e=$("<input/>",{ val: $(a[i]).attr("href"), on: { input: function(x) { return function(){ $(a[x]).attr("href",this.value); $(c[x]).attr("id",this.value); } }(i) } }); var j=$("<input/>",{ val: $(a[i]).html(), on: { input: function(x) { return function(){ $(a[x]).html(this.value); // } }(i) } }); var z=$("</p>",{ data: { b: "b" } }); var zz=$("<textarea/>",{ text: $(c[i]).html(), on: { input: function(x) { return function(){ $(c[x]).html(this.value); } }(i) } }); z.data("b",a[i]); z.data("bb",c[i]); z.append([e,j,"<br>",zz]);//добавляем в параграф d[i]=z; } $("#edit").text(""); $("#edit").append(d); } ff(); //функция сотрировки $("#edit").sortable({ stop: function(a, b) { var c = $.map($("#edit p"), function(a,k) { return $(a).data("b") }); var d = $.map($("#edit p"), function(a,k) { return $(a).data("bb") }); $("#menu").append(c); $("#content").append(d); // ff(); } }); //функция которая добавляет ссылки $("#addlink").click(function() { var a = $("#href").val() || "#", b = $("#text").val() || "add"; c = $("#textarea").val() || "add"; // alert(c); $("<a/>", { href: a, text: b }).appendTo("#menu"); $("#href, #text").val("") $("<div/>",{ id: a, text: c }).appendTo("#content"); $("#edit p").remove(); ff(); }); $("#select").change(function() { if ($("#select option:selected").val() == 'textarea') { $("#options").html('text: <textarea id="textarea"></textarea>'); } if ($("#select option:selected").val() == 'img') { $("#options").html('link: <input id="image">'); } }); }); </script> </head> <body> <div id="menu"> <a href="#dfdf">1df</a> <a href="#fgg44">2fsdfsd</a> <a href="#Df324">3dsfdsf</a> </div> <hr> <div id="content"> <div id="dfdf">12</div> <div id="fgg44">45yth</div> <div id="Df324">64h<b>eh</b>w</div> </div> <hr> <div id="edit"></div> <hr> <br> <div id="add"><input id="href"><input id="text"> <div id="options"> <select name="select" id="select"><option value="" selected>Выберите</option><option value="textarea">Текст</option><option value="img">Картинка</option></select> </div> <input id="addlink" name="" type="button" value="add"> </div> </body> </html> |
добавление рекламы гугл и яндекс после тегов h3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<script type="text/javascript"> //<h3> var count_char=300;//количество символов var count_yandex=2;// var text_yandex="<br>yandex ad"; var text_google="<br>google ad"; var text=document.body.innerHTML; //alert(text); //var regex=/<h3>|<\/h3>(?:(?:\S|.)*)<h3>|<\/h3>/g; var regex=/<h3>((?:.|\r|\n)*?)<h3>/g; var flag=[]; while(r=regex.exec(text)){ // alert("r= "+r[0].length); var str=r[0]; str=str.replace(/<[^<>]*script[^<>]*>(?:(?:.|\r|\n)*?)<\/script>/g,''); str=str.replace(/<[^<>]*?>/g,''); str=str.replace(/\s+/g,' '); // alert("str= "+str.length); if(str.length>count_char){ flag[flag.length]=1; // alert(str); } else{ flag[flag.length]=0; } regex.lastIndex=regex.lastIndex-10; } var s=document.querySelectorAll("h3"); /*alert (s.length); alert(s[0].outerHTML); alert(s[s.length-1].textContent);*/ //s[0].textContent="hellow"; var count=0; for(var i=0;i<s.length;i++){ if(count<count_yandex && flag[i]==1){ s[i].outerHTML=s[i].outerHTML.trim()+"\r\n"+text_yandex; count++; continue; } else if(flag[i]==1){ s[i].outerHTML=s[i].outerHTML.trim()+"\r\n"+text_google; } } //s[0].outerHTML=s[0].outerHTML+"hellow"; </script> |
[youtube]https://www.youtube.com/watch?v=3w774j721sI[/youtube]