JS插件无法识别动态添加的元素

时间:2019-01-31 16:40:07

标签: javascript html

CloudZoom是一个插件,可让您在悬停时放大图片。它要求一个元素具有“ cloudzoom”类,并处理其他所有内容。如果我手动创建元素,一切都会很好。但是,如果我去做了里面脚本的window.onload函数(因为我需要从数据库获取它),这是行不通的。

<html>
<head>
    <title>Cloud Zoom</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <!-- Include jQuery. -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
    <script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script>
    <!-- Include Cloud Zoom CSS. -->
    <link rel="stylesheet" type="text/css" href="CloudZoom/cloudzoom.css"/>

    <!-- Include Cloud Zoom script. -->
    <script type="text/javascript" src="CloudZoom/cloudzoom.js"></script>

    <!-- Call quick start function. -->
    <script type="text/javascript">
        //
        CloudZoom.quickStart();
    </script>

    <script>

        window.onload = function () {
            //fetching json with name and img src link
            fetch('http://localhost:8080/get')
                .then(function (response) {
                    return response.json();
                })
                .then(function (myJson) {
                    //getting img link from db
                    arr = JSON.stringify(myJson);
                    console.log(myJson[0][2]);
                    //creating img element
                    img = document.createElement('img');
                    img.setAttribute('id', 'clothImg');
                    img.setAttribute('class', 'cloudzoom');
                    img.setAttribute('src', myJson[0][2]);
                    //inserting inside DOM
                    document.getElementById('surround').appendChild(img);

                });
        }

    </script>
</head>
<body>
<div id=surround>
</div>

<style>
    #surround {
        width: 50%;
        min-width: 256px;
        max-width: 480px;
    }

    /* Image expands to width of surround */
    img.cloudzoom {
        width: 100%;
    }
</style>
</body>
</html>

我希望添加的图像是通过插件

识别的

1 个答案:

答案 0 :(得分:1)

您只需要在新添加的元素上应用CloudZoom jQuery method。当您使用jQuery时,我还建议您更多使用它:

$(function () {
    //fetching json with name and img src link
    fetch('http://localhost:8080/get')
        .then(function (response) {
            return response.json();
        })
        .then(function (myJson) {
            //getting img link from db
            console.log(myJson[0][2]);
            //creating img element
            var $img = $('<img>', {
                "id": 'clothImg',
                "class": 'cloudzoom',
                "src": myJson[0][2]
            });
            $img.appendTo("#surround"); //inserting inside DOM
            $img.CloudZoom(); // <--
        });
});