У меня есть 3 файла с php и js. в первом файле я загружаю некоторую информацию и показываю ее пользователю, тогда пользователь может их изменить. для отображения другой информации пользователю i перезагружать часть моей страницы с некоторым кодом, который они находятся во втором php-файле. Я помещаю их в <div id='show_album'>my data</div>
и меняю их на второй php-файл. для первого запуска моего javascript-кода работает нормально, но после перезагрузки части страницы он никогда не работает. что я должен изменить в коде, который он работает после перезагрузки?Почему этот код javascript не работает после перезагрузки части моей страницы с помощью ajax?
это часть кода, который может перезарядить Div элемент с AJAX:
<select onchange="showList('showalbum.php?change=',this.value,'show_album')"><option value='1'>1</option> <option value='2'>2</option></select>
в этой части кода, в первой странице я перезагрузить мой DIV элемент с новыми данными. то в новых данных у меня есть что-то вроде этого:
<a href="albums/album1/SAM_2676.jpg" rel="lightbox">size of picture: 460*345</a>
, которые показывают связь изображения к пользователю и когда пользователь нажимает на нее, с JavaScript я показать его пользователю на этой странице и на моей другой информации, которую пользователь может закрыть it.but теперь этот rel = "lightbox" не работает, и когда пользователь нажимает на ссылку, этот снимок открывается в том же окне.
это мой Javascript код и <head>
я определить его:
/*
\t Table of Contents
\t -----------------
\t Configuration
\t
\t Functions
\t - getPageScroll()
\t - getPageSize()
\t - pause()
\t - getKey()
\t - listenKey()
\t - showLightbox()
\t - hideLightbox()
\t - initLightbox()
\t - addLoadEvent()
\t Function Calls
\t - addLoadEvent(initLightbox)
*/
//
// Configuration
//
// If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = './LightBox/loading.gif';
var closeButton = './LightBox/close.gif';
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){
\t var yScroll;
\t if (self.pageYOffset) {
\t \t yScroll = self.pageYOffset;
\t } else if (document.documentElement && document.documentElement.scrollTop){ \t // Explorer 6 Strict
\t \t yScroll = document.documentElement.scrollTop;
\t } else if (document.body) {// all other Explorers
\t \t yScroll = document.body.scrollTop;
\t }
\t arrayPageScroll = new Array('',yScroll)
\t return arrayPageScroll;
}
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
\t
\t var xScroll, yScroll;
\t if (window.innerHeight && window.scrollMaxY) { \t
\t \t xScroll = document.body.scrollWidth;
\t \t yScroll = window.innerHeight + window.scrollMaxY;
\t } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
\t \t xScroll = document.body.scrollWidth;
\t \t yScroll = document.body.scrollHeight;
\t } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
\t \t xScroll = document.body.offsetWidth;
\t \t yScroll = document.body.offsetHeight;
\t }
\t
\t var windowWidth, windowHeight;
\t if (self.innerHeight) { \t // all except Explorer
\t \t windowWidth = self.innerWidth;
\t \t windowHeight = self.innerHeight;
\t } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
\t \t windowWidth = document.documentElement.clientWidth;
\t \t windowHeight = document.documentElement.clientHeight;
\t } else if (document.body) { // other Explorers
\t \t windowWidth = document.body.clientWidth;
\t \t windowHeight = document.body.clientHeight;
\t } \t
\t
\t // for small pages with total height less then height of the viewport
\t if(yScroll < windowHeight){
\t \t pageHeight = windowHeight;
\t } else {
\t \t pageHeight = yScroll;
\t }
\t // for small pages with total width less then width of the viewport
\t if(xScroll < windowWidth){
\t \t pageWidth = windowWidth;
\t } else {
\t \t pageWidth = xScroll;
\t }
\t arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
\t return arrayPageSize;
}
//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
\t var now = new Date();
\t var exitTime = now.getTime() + numberMillis;
\t while (true) {
\t \t now = new Date();
\t \t if (now.getTime() > exitTime)
\t \t \t return;
\t }
}
//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
\t if (e == null) { // ie
\t \t keycode = event.keyCode;
\t } else { // mozilla
\t \t keycode = e.which;
\t }
\t key = String.fromCharCode(keycode).toLowerCase();
\t
\t if(key == 'x'){ hideLightbox(); }
}
//
// listenKey()
//
function listenKey() { \t document.onkeypress = getKey; }
\t
//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
\t // prep objects
\t var objOverlay = document.getElementById('overlay');
\t var objLightbox = document.getElementById('lightbox');
\t var objCaption = document.getElementById('lightboxCaption');
\t var objImage = document.getElementById('lightboxImage');
\t var objLoadingImage = document.getElementById('loadingImage');
\t var objLightboxDetails = document.getElementById('lightboxDetails');
\t
\t var arrayPageSize = getPageSize();
\t var arrayPageScroll = getPageScroll();
\t // center loadingImage if it exists
\t if (objLoadingImage) {
\t \t objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height)/2) + 'px');
\t \t objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width)/2) + 'px');
\t \t objLoadingImage.style.display = 'block';
\t }
\t // set height of Overlay to take up whole page and show
\t objOverlay.style.height = (arrayPageSize[1] + 'px');
\t objOverlay.style.display = 'block';
\t // preload image
\t imgPreload = new Image();
\t imgPreload.onload=function(){
\t \t objImage.src = objLink.href;
\t \t // center lightbox and make sure that the top and left values are not negative
\t \t // and the image placed outside the viewport
\t \t var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height)/2);
\t \t var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width)/2);
\t \t
\t \t objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
\t \t objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
\t \t objLightboxDetails.style.width = imgPreload.width + 'px';
\t \t
\t \t if(objLink.getAttribute('title')){
\t \t \t objCaption.style.display = 'block';
\t \t \t //objCaption.style.width = imgPreload.width + 'px';
\t \t \t objCaption.innerHTML = objLink.getAttribute('title');
\t \t } else {
\t \t \t objCaption.style.display = 'none';
\t \t }
\t \t
\t \t // A small pause between the image loading and displaying is required with IE,
\t \t // this prevents the previous image displaying for a short burst causing flicker.
\t \t if (navigator.appVersion.indexOf("MSIE")!=-1){
\t \t \t pause(250);
\t \t }
\t \t if (objLoadingImage) { \t objLoadingImage.style.display = 'none'; }
\t \t objLightbox.style.display = 'block';
\t \t // After image is loaded, update the overlay height as the new image might have
\t \t // increased the overall page height.
\t \t arrayPageSize = getPageSize();
\t \t objOverlay.style.height = (arrayPageSize[1] + 'px');
\t \t
\t \t // Check for 'x' keypress
\t \t listenKey();
\t \t return false;
\t }
\t imgPreload.src = objLink.href;
var e = document.getElementById('gand');
e.style.display = 'none';
\t
}
//
// hideLightbox()
//
function hideLightbox()
{
\t // get objects
\t objOverlay = document.getElementById('overlay');
\t objLightbox = document.getElementById('lightbox');
\t // hide lightbox and overlay
\t objOverlay.style.display = 'none';
\t objLightbox.style.display = 'none';
\t
\t // disable keypress listener
\t document.onkeypress = '';
var e = document.getElementById('gand');
e.style.display = 'block';
}
//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
\t
\t if (!document.getElementsByTagName){ return; }
\t var anchors = document.getElementsByTagName("a");
\t // loop through all anchor tags
\t for (var i=0; i<anchors.length; i++){
\t \t var anchor = anchors[i];
\t \t if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
\t \t \t anchor.onclick = function() {showLightbox(this); return false;}
\t \t }
\t }
\t // the rest of this code inserts html at the top of the page that looks like this:
\t //
\t // <div id="overlay">
\t // \t \t <a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
\t // \t </div>
\t // <div id="lightbox">
\t // \t \t <a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
\t // \t \t \t <img id="closeButton" />
\t // \t \t \t <img id="lightboxImage" />
\t // \t \t </a>
\t // \t \t <div id="lightboxDetails">
\t // \t \t \t <div id="lightboxCaption"></div>
\t // \t \t \t <div id="keyboardMsg"></div>
\t // \t \t </div>
\t // </div>
\t
\t var objBody = document.getElementsByTagName("body").item(0);
\t
\t // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
\t var objOverlay = document.createElement("div");
\t objOverlay.setAttribute('id','overlay');
\t objOverlay.onclick = function() {hideLightbox(); return false;}
\t objOverlay.style.display = 'none';
\t objOverlay.style.position = 'absolute';
\t objOverlay.style.top = '0';
\t objOverlay.style.left = '0';
\t objOverlay.style.zIndex = '90';
\t objOverlay.style.width = '100%';
\t objBody.insertBefore(objOverlay, objBody.firstChild);
\t
\t var arrayPageSize = getPageSize();
\t var arrayPageScroll = getPageScroll();
\t // preload and create loader image
\t var imgPreloader = new Image();
\t
\t // if loader image found, create link to hide lightbox and create loadingimage
\t imgPreloader.onload=function(){
\t \t var objLoadingImageLink = document.createElement("a");
\t \t objLoadingImageLink.setAttribute('href','#');
\t \t objLoadingImageLink.onclick = function() {hideLightbox(); return false;}
\t \t objOverlay.appendChild(objLoadingImageLink);
\t \t var objLoadingImage = document.createElement("img");
\t \t objLoadingImage.src = loadingImage;
\t \t objLoadingImage.setAttribute('id','loadingImage');
\t \t objLoadingImage.style.position = 'absolute';
\t \t objLoadingImage.style.zIndex = '150';
\t \t objLoadingImageLink.appendChild(objLoadingImage);
\t \t imgPreloader.onload=function(){}; \t // \t clear onLoad, as IE will flip out w/animated gifs
\t \t return false;
\t }
\t imgPreloader.src = loadingImage;
\t // create lightbox div, same note about styles as above
\t var objLightbox = document.createElement("div");
\t objLightbox.setAttribute('id','lightbox');
\t objLightbox.style.display = 'none';
\t objLightbox.style.position = 'absolute';
\t objLightbox.style.zIndex = '100'; \t
\t objBody.insertBefore(objLightbox, objOverlay.nextSibling);
\t
\t // create link
\t var objLink = document.createElement("a");
\t objLink.setAttribute('href','#');
\t objLink.setAttribute('title','براي بستن کليک کنيد');
\t objLink.onclick = function() {hideLightbox(); return false;}
\t objLightbox.appendChild(objLink);
\t // preload and create close button image
\t var imgPreloadCloseButton = new Image();
\t // if close button image found,
\t imgPreloadCloseButton.onload=function(){
\t \t var objCloseButton = document.createElement("img");
\t \t objCloseButton.src = closeButton;
\t \t objCloseButton.setAttribute('id','closeButton');
\t \t objCloseButton.style.position = 'absolute';
\t \t objCloseButton.style.zIndex = '200';
\t \t objLink.appendChild(objCloseButton);
\t \t return false;
\t }
\t imgPreloadCloseButton.src = closeButton;
\t // create image
\t var objImage = document.createElement("img");
\t objImage.setAttribute('id','lightboxImage');
\t objLink.appendChild(objImage);
\t
\t // create details div, a container for the caption and keyboard message
\t var objLightboxDetails = document.createElement("div");
\t objLightboxDetails.setAttribute('id','lightboxDetails');
\t objLightbox.appendChild(objLightboxDetails);
\t // create caption
\t var objCaption = document.createElement("div");
\t objCaption.setAttribute('id','lightboxCaption');
\t objCaption.style.display = 'none';
\t objLightboxDetails.appendChild(objCaption);
\t // create keyboard message
\t var objKeyboardMsg = document.createElement("div");
\t objKeyboardMsg.setAttribute('id','keyboardMsg');
\t objKeyboardMsg.innerHTML = 'براي بستن کليد <kbd>x</kbd> را فشار دهيد';
\t objLightboxDetails.appendChild(objKeyboardMsg);
}
//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{ \t
\t var oldonload = window.onload;
\t if (typeof window.onload != 'function'){
\t window.onload = func;
\t } else {
\t \t window.onload = function(){
\t \t oldonload();
\t \t func();
\t \t }
\t }
}
addLoadEvent(initLightbox); \t // run initLightbox onLoad
и у меня есть CSS для этого Js, что это не importat но я пишу это здесь:
#lightbox {
\t background-color: #eee;
\t padding: 10px;
\t border-bottom: 2px solid #666;
\t border-right: 2px solid #666;
}
#lightboxDetails {
\t font-size: 0.8em;
\t padding-top: 0.4em;
}
#lightboxCaption {
\t float: left;
}
#keyboardMsg {
\t float: right;
}
#closeButton {
\t top: 5px;
\t right: 5px;
}
#lightbox img {
\t border: none;
\t clear: both;
}
#overlay img {
\t border: none;
}
#overlay {
\t background: url(../LightBox/overlay.png);
}
* html #overlay {
\t background-color: #000;
\t filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="../LightBox/overlay.png", sizingMethod="scale");
\t filter: alpha(opacity=70);
\t opacity: 0.7;
}
Я думаю, что этот код просто запускается один раз на window.load() и после перезагрузки части страницы он не может снова загрузиться и не работает.
как я могу решить эту проблему? tnks для чтения на мой вопрос ...
необходимо инициализировать код лайтбокса после ввода новых элементов или использовать делегирование событий – charlietfl
как я могу это сделать в своем коде? – parham2501