Вопрос от новичка.
Я просто попробую сделать сайт фотогалереи по образцу шаблона сайта. Мои фотографии находятся в локальной папке на сервере IIS.
Первая задача - загрузить все подпапки из основных папок: Это прекрасно работает!
<li class="colorlib-active">
<?php
if ($handle = opendir('images')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && $entry != ".htaccess" && $entry != ".htpasswd"){
echo '<a href="#" onclick=photogallery("images/'.$entry.'")> '.$entry.'</a><br>'; }
}
closedir($handle);
}
?>
</li>
Затем функция photogallery (): после щелчка по подпапке, затем мы можем найти все jpg-файлы и приписать их. Это также прекрасно работает!
<script>
function photogallery($dir){
$.ajax({
url: $dir,
success: function(data){
$(data).find('a[href$=".jpg"]').each(function () {
var filename = this.href.replace(window.location.host, "").replace("https://", "");
var fileurl = filename;
var para = document.createElement("div");
para.setAttribute("class", "col-md-4 ftco-animate");
var para2 = document.createElement("a");
para2.setAttribute("href", filename);
para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");
para2.setAttribute("style", "background-image: url("+fileurl+");");
document.getElementById("photoplace").appendChild(para).appendChild(para2);
});
}
});
}
</script>
Это динамически обновляет div photoplace:
<section class="ftco-section-2">
<div class="photograhy">
<div class="row no-gutters" id="photoplace">
</div>
</div>
</section>
Так что проблема в том, что изображения не отображаются на странице, потому что класс ftco-animate не будет работать. Я удаляю этот класс, и теперь я вижу картинки. После клика по картинке класс image-popup не будет работать.
Тем не менее, если я вызову функцию напрямую без ajax:
<script>
function test($dir2){
var para = document.createElement("div");
para.setAttribute("class", "col-md-4 ftco-animate");
var para2 = document.createElement("a");
para2.setAttribute("href", $dir2);
para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");
para2.setAttribute("style", "background-image: url("+$dir2+");");
document.getElementById("photoplace").appendChild(para).appendChild(para2);
}
</script>
По вызову: test("images/folder1/IMG_20200410_0128.jpg");
Это прекрасно работает!
Не могли бы вы рассказать, что случилось с кодом внутри ajax или где это не так? Спасибо.
Chrome Консоль показывает следующие ошибки:
js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:126 Uncaught pd {message: "Map: Expected mapDiv of type Element but was passed null.", name: "InvalidValueError", stack: "Error↵ at new pd (https://maps.googleapis.com/m…init (myurladdress/js/google-map.js:44:15)"}message: "Map: Expected mapDiv of type Element but was passed null."name: "InvalidValueError"stack: "Error↵ at new pd (https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:56:227)↵ at Object._.qd (https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:56:337)↵ at new Gi (https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:126:50)↵ at init (myurladdress/js/google-map.js:44:15)"__proto__: Error
Gi @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:126
init @ google-map.js:44
load (async)
_.N.addDomListener @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:184
(anonymous) @ google-map.js:62
DevTools failed to load SourceMap: Could not load content for myurladdress/js/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for myurladdress/js/bootstrap.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for myurladdress/js/aos.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for myurladdress/css/aos.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
util.js:230 Google Maps JavaScript API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required
uz.o @ util.js:230
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:140
Promise.then (async)
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:140
setTimeout (async)
Aj @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:140
google.maps.Load @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:14
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:233
(anonymous) @ js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false:233
и:
throw _.qd("Map: Expected mapDiv of type Element but was passed "+a+".");if("string"===typeof a)throw _.qd("Map: Expected mapDiv of type Element but was passed string '"+a+"'.");var d=b||{};d.noClear||_.Bi(a);var e="undefined"==typeof document?null:document.createElement("div");e&&a.appendChild&&(a.appendChild(e),e.style.width=e.style.height="100%");if(!(_.z.devicePixelRatio&&_.z.requestAnimationFrame||_.Tg[43]))throw _.P("controls").then(function(m){m.Oh(a)}),
Обновление! Пожалуйста, забудьте предыдущие и после многих часов проверки у меня один вопрос!
Какая разница в следующих двух способах вызова функции? (потому что последний работает быстро!)
<script>
function loadimages(){
$imurl ="photos/gallery1/IMG_20200410_0128.jpg";
var para = document.createElement("div");
var para.setAttribute("class", "col-md-4 ftco-animate");
para2 = document.createElement("a");
para2.setAttribute("href", $imurl);
para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");
para2.setAttribute("style", "background-image: url('"+$imurl+"');");
document.getElementById("photoplace").appendChild(para).appendChild(para2);
}
document.getElementById("clickMe").onclick = function () { loadimages(); };
</script>
или
<script>
function loadimages(){
$imurl ="photos/gallery1/IMG_20200410_0128.jpg";
var para = document.createElement("div");
var para.setAttribute("class", "col-md-4 ftco-animate");
para2 = document.createElement("a");
para2.setAttribute("href", $imurl);
para2.setAttribute("class", "photography-entry img image-popup d-flex justify-content-center align-items-center");
para2.setAttribute("style", "background-image: url('"+$imurl+"');");
document.getElementById("photoplace").appendChild(para).appendChild(para2);
}
loadimages();
</script>
Действительно, почему этот последний код работает быстро и кнопка html не может активировать функцию быстро?