Солянка JavaScript

You can't request more than 20 challenges without solving them. Your previous challenges were flushed.


В этом посте по мере моего узнавания будут появляться полезные функции и приемы работы с JavaScript. Если для вас это очевидные вещи, просто не читайте (:

Расширение обработчика onclick

Задача: в приложении имелась ссылка, сгенеренная perlом, со своими атрибутами и своим определенным onclick в <a....>. Мне нужно было вызвать еще одну функцию на клик по ссылке, перед ее собственным обработчиком, не меняя код генерации ссылки.

Решение: ссылку я обернула в span

<span id="mylink">
<a ...>Сама ссылка</a>
</span>

Далее в конце body в тегах <script> .. </script>, (или в обработчик onload) поместила функцию changeLinkOnclick()

function changeLinkOnclick () { 
	//Взяли все ссылки внутри спана с помощью prototype.js
	var mylink = \$('mylink').getElementsByTagName('a'); 
	//сохранили старый обработчик onclick
	var func = mylink[0].onclick;
	//проверка на всякий случай
	if(typeof(func ) == 'function'){ 
		//новый onclick
		mylink[0].onclick = function () { 
			//функция, которую хотели добавить
			saveScript();
			//вызов старого обработчика
			func.call(this);
		}
	}
	return false;	
}

Подключение js скрипта из другого скрипта

Задача: в нашем приложении на перле файлы скриптов подключаются специальным образом из определенной папочки. Мне потребовалось подключить еще один скрипт из другого места. Расширять старый механизм подключения нехорошо.

Решение: в нужном участке body в тегах <script> .. </script> вызвала функцию addJavascript('..../new.js', 'head').

function addJavascript(jsname, pos) {
	var where = document.getElementsByTagName(pos)[0];
	var s = document.createElement('script');
	s.setAttribute('type','text/javascript');
	s.setAttribute('src',jsname);
	where.appendChild(s);
}

При написании поста я неоднократно пользовалась инструментом подготовки кода к публикации (:

Комментарии

louboutin are likely to be made of cheaper materials, and are therefore more prone to chipping and damage. Genuine christian louboutin uk is crafted to a high standard, making this premium jewellery both desirable and practical. With such a huge range of louboutin shoes available,makes the perfect gift for ladies of any age. If you are a louboutin shoes collector and you are concerned about being given imitation as gifts, then why not set up a Club account, and create a wish list? christian louboutin shoes can be found for less when you shop on the Internet. louboutin boots are now available online for discounted prices. christian louboutin sandals is one of the most recognized name brands in the world of high fashion. You will find A-list celebrities such as Sarah Jessica Parker, Janet Jackson and Nicole Kidman wearing louboutin pumps. Since it's conception, the louboutin boots has been produced into a variety of designs, colors, shapes, and styles that have won top picks of millions of women the world over. You are sure to find something of your liking when shopping from either a christian louboutin wedges store or outlet for. Many of the listed hermes handbags found in the main stores or department stores can be found in the outlets, so get out there and start shopping! A great place to shop for gorgeous hermes birkin purse is online. Shopping online will save you up to 70% on all of the latest hermes sale styles. For those of you wanting to save big bucks on your hermes evelyne, try shopping online. You can find great buys and save on the hottest designer Hermes handbags on sale through online auctions.

Отправить комментарий

Содержание этого поля является приватным и не предназначено к показу.
  • Разрешаю теги: <a> <em> <strong> <pre> <ul> <ol> <li>
  • Строки и параграфы переносятся автоматически.
  • Адреса страниц и электронной почты автоматически преобразуются в ссылки.

Подробнее о форматировании

Image CAPTCHA
Регистр символов учитывается.