简体   繁体   English

动态添加<img>通过 PHP 循环标记,通过在每个循环上调用 JavaScript 函数

[英]Dynamically add <img> tags with via PHP loop, via calling a JavaScript function on each loop

I have a PHP function that loops through image results in a database, formats them with HTML, then returns the variable containing the HTML layout to my page.php.我有一个 PHP 函数,它在数据库中循环图像结果,用 HTML 格式化它们,然后将包含 HTML 布局的变量返回到我的 page.php。 This is all working okay, but in the loop I have some script tags that call a function in my script.js file.这一切正常,但在循环中,我有一些脚本标签在我的 script.js 文件中调用一个函数。 It takes two parameters (url and count).它需要两个参数(url 和 count)。 I am trying to pass the url of the result from the database to the function, create a new img element, and append the passed url to the src attribute of the newly created img tag.我试图将结果的 url 从数据库传递给函数,创建一个新的img元素,并将传递的 url 附加到新创建的 img 标签的 src 属性。 This appears to be working so far - when I console.log the result, I get a load of <img> tags, all with corresponding src attached to them.到目前为止,这似乎有效 - 当我 console.log 结果时,我得到了一堆<img>标签,所有标签都附加了相应的 src。

I am having trouble with actually getting these back to the front end, though.不过,我在实际将这些返回到前端时遇到了麻烦。

My code below shows the part of the php that gets looped through, followed be the Javascript function it calls on each loop.我下面的代码显示了循环通过的 php 部分,然后是它在每个循环中调用的 Javascript 函数。

    public function getResultsHtml($page, $pageSize, $term) {
        $fromLimit = ($page - 1) * $pageSize;
        $query = $this->con->prepare("SELECT * FROM images 
            WHERE (title LIKE :term
            OR alt LIKE :term) AND broken=0
            ORDER BY clicks DESC
            LIMIT :fromLimit, :pageSize");

        $searchTerm = "%" . $term . "%";
        $query->bindParam(":term", $searchTerm);
        $query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
        $query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
        $query->execute();

        $resultsHtml = "<div class='image-results'>";

        $count = 0;
        while($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $count++;
            $id = $row["id"];
            $imgUrl = $row["imgUrl"];
            $siteUrl = $row["siteUrl"];             
            $title = $row["title"];
            $alt = $row["alt"];

            if($title){
                $displayText = $title;
            } else if ($alt) {
                $displayText = $alt;
            } else {
                $displayText = $imgUrl;
            }

            $resultsHtml .= "<div class='grid-item image$count'>
                                <a href='$imgUrl'>
                                    <script>
                                        document.addEventListener('DOMContentLoaded', function() {
                                            loadImage(\"$imgUrl\", \"image$count\");
                                        });
                                    </script>
                                    <span class='details'>$displayText</span>
                                </a>

                            </div>";
            }
            $resultsHtml .= "</div>";
            return $resultsHtml;
        }

    var loadImage = function(src, className){

        var image = document.createElement("img");
        var aTag = document.querySelectorAll("." + className + " a");

        image.onload = function(){
            aTag.innerHTML = image;
        };
        image.onerror = function(){

        };

            image.setAttribute("src", src);

    }

At the moment I'm not geting any results at the front end.目前我在前端没有得到任何结果。 In the page source, I can see that inside each anchor tag are script tags, which show the function preloaded with the parameters ( loadImage(http://www.com, image22) ), but it isn't actually getting a return from the function.在页面源代码中,我可以看到每个锚标记内部都是脚本标记,它显示了预加载参数的函数( loadImage(http://www.com, image22) ),但实际上并没有从功能。

The solution for this with jQuery is below, but I really don't want to use jQuery!使用 jQuery 的解决方案如下,但我真的不想使用 jQuery!

            function loadImage(src, className) {

                var image = $("<img>");

                image.on("load", function() {
                    $("." + className + " a").append(image);
                });

                image.on("error", function() {

                });

                image.attr("src", src);

            }

I know that there is some trouble with dynamically writing <script> tags with .innerHTML , but I don't think this is the problem as the script tags are written before the function is called.我知道使用.innerHTML动态编写<script>标签存在一些问题,但我认为这不是问题,因为脚本标签是在调用函数之前编写的。

I think I have something firing in the wrong order, or I'm missing something that jQuery handles automatically with the .append function.我想我有一些东西以错误的顺序触发,或者我错过了 jQuery 使用 .append 函数自动处理的东西。

I have also tried aTag.appendChild(image);我也试过aTag.appendChild(image); , which also gives no results. ,这也没有结果。

I have been using jQuery for a few months, but I am trying to learn Vanilla JS thoroughly - I'm trying to grasp how the jQuery functions actually work, rather than just relying on them blindly.我已经使用 jQuery 几个月了,但我正在尝试彻底学习 Vanilla JS - 我试图掌握 jQuery 函数的实际工作方式,而不是盲目地依赖它们。

Any help is massively appreciated!任何帮助都非常感谢!

Beware of that querySelectorAll() returns an array-like NodeList ( https://developer.mozilla.org/en-US/docs/Web/API/NodeList ), so it should be like this:当心querySelectorAll()返回一个类似数组的 NodeList ( https://developer.mozilla.org/en-US/docs/Web/API/NodeList ),所以它应该是这样的:

(If you only want one element returned user querySelector() , then you don't need the loop) (如果你只想要一个元素返回用户querySelector() ,那么你不需要循环)

 function loadImage(src, className) { var image = document.createElement("img"); image.src = src; image.onload = function() { var tags = document.querySelectorAll("." + className + " a"); for (var i = 0; i < tags.length; i++) { tags[i].appendChild(image); } } }
 <div class='grid-item image2'> <a href='https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg'> <script> document.addEventListener('DOMContentLoaded', function() { loadImage("https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg", "image2"); }); </script> <span class='details'>Star Wars 1</span> </a> </div>

The problem is that you are using querySelectorAll , which returns a NodeList instead of a single DOM node.问题是您使用的是querySelectorAll ,它返回一个NodeList而不是单个 DOM 节点。 This means, you have to iterate over the NodeList and append the image to all the nodes within.这意味着,您必须遍历NodeList并将图像附加到其中的所有节点。 For this, you have can either create new copies for each place you want to insert the image, or use cloneNode multiple times.为此,您可以为要插入图像的每个位置创建新副本,或者多次使用cloneNode

 var each = function (xs, func) { for (var i = 0; i < xs.length; i += 1) { func(xs[i]); } return xs; } var loadImage = function(src, className){ var image = document.createElement("img"); var aTag = document.querySelectorAll("." + className + " a"); image.onload = function(){ each(aTag, function (a) { a.appendChild(image.cloneNode()); }); }; image.onerror = function(){}; image.alt = ''; image.src = src; } loadImage('http://www.fillmurray.com/500/300', 'wrap')
 <div class="wrap"> <a href="#"></a> <a href="#"></a> <a href="#"></a> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM