在图像上单击创建一个新对象,并使用其属性更新HTML

时间:2016-12-13 19:48:15

标签: javascript

我想在点击图片时创建一个新对象

我正在尝试以下代码(我很不高兴):

<body>
        <h1>Container Verwaltung</h1>
        <p>Welche Containerart wollen Sie anlegen ?</p>
        <div>
            <a href='#' id='gray'>  <img src='gray.png'   width='201' height='423'></a>
            <a href='#' id='yellow'><img src='yellow.png' width='201' height='423'></a>
            <a href='#' id='blue'>  <img src='blue.png'   width='201' height='423'></a>
        </div>

        <p>Liste Ihrer vorhandenen Containers:</p>
        <div id='data'>Containers to be shown</div>

        <script src="containerVerwaltung.js"></script>
    </body>

我的Javascript目前看起来像这样,但我无法得到它

// function that has to create the new object on button click:
function addContainerBlue(e) {
    e.preventDefault();
    var containerBlue = new Object();
    containerBlue.name = "blue";
    containerBlue.use  = "paper";
    return containerBlue;
}

// listener for the click:
var blueImageLink = document.getElementById("blue");
blueImageLink.addEventListener("click", addContainerBlue);

// provide info about the object in the HTML:
document.getElementById('data').innerHTML = containerBlue.name;

1 个答案:

答案 0 :(得分:0)

您应该在click处理程序中设置innerHTML,因为只有您正在创建对象。

    // Now this is a global variable
    var containerBlue = new Object();
    function addContainerBlue(e) {
        e.preventDefault();
        containerBlue.name = "blue";
        containerBlue.use  = "paper";
        document.getElementById('data').innerHTML = containerBlue.name;
    }

// listener for the click:
var blueImageLink = document.getElementById("blue");
blueImageLink.addEventListener("click", addContainerBlue);

现在,当您单击 addContainerBlue 按钮时,您将创建对象并将innerHTML设置为containerBlue的name属性。