简体   繁体   中英

How to catch the error while setting html string to div's innerHTML

I am trying to set innerHTML of DIV with the HTML string. The HTML string may have buttons with onclick events. onclick event might have attached to some function which might not be availabe with the HTML String.

For example,

HTML String:

var htmlString = "<div><img onerror='someFunc()' src='path/to/image'>Click Me </img> </div>";

In the above html string, the someFunc function is NOT available with the HTML String.

Setting the innerHTML:

var div = document.createElement('div');
div.innerHTML = htmlString;

So, when i set the htmlString to innerHTML of div, it throws Uncaught ReferenceError: someFunc is not defined

I tried to catch the error using try catch but catch block is not executed.

Jsfiddle here

Please help me.

Here i have demonstrated without using a try catch. Working on chrome. Im not sure how it will work on other browsers.

var images = ['/asd','anotherurl'];

for (i = 0; i < images.length; i++) { 
    console.log(images[i]);
    var img = new Image();

    img.src = images[i];
    if(img.height > 0){
        var div = document.createElement('div');
        div.appendChild(img);
        document.getElementById('div').appendChild(div);
    }
}

JsFiddle http://jsfiddle.net/q8mo2df8/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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