Adding to innerHTML correct syntax

故事扮演 提交于 2019-12-11 23:18:30

问题


What is the correct syntax if I want to add content to an element using innerHTML. Below is my non working example:

   openNewWindow: function(content) {
popupWin = window.open(content,
    'open_window',
    'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')
},

for (var index in mv.exifImages) {
        ele.innerHTML += "<p onclick = openNewWindow(mv.exifImages[index]> image" + index + "</p>";
    }

回答1:


i think it is. variable index has local scope

for (var index in mv.exifImages) {
        ele.innerHTML += "<p onclick = 'openNewWindow(\"" + mv.exifImages[index] + "\")'> image" + index + "</p>";
    }



回答2:


Use appendChild:

var myelement = document.getElementById("myelement");
myelement.appendChild( document.createTextNode("Example text inside myelemen") );

This is better that overwriting innerHTML, as it preserves onclick events for example:
Is it possible to append to innerHTML without destroying descendants' event listeners?




回答3:


innerHTML is not your problem, your code is lacking context.

    openNewWindow: function(content) {
        popupWin = window.open(content,
            'open_window',
            'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0');
        // call to window.open ended here
    },
    // judging by the definition of openNewWindow and the comma above,
    // we are inside an object definition!

    // you cannot embed a for loop inside an object definition!!!
    for (var index in mv.exifImages) {
        ele.innerHTML += "<p onclick = openNewWindow(mv.exifImages[index]> image" + index + "</p>";
    }

Put your for loop somewhere sensible, like inside a function, or actually show us the error you are getting.



来源:https://stackoverflow.com/questions/14977179/adding-to-innerhtml-correct-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!