JavaScript: Escaping double quotes in HTML
问题 How can I prevent the images[i].title below from breaking the HTML if it contains double quotes? for (i=0; i<=images.length-1; i++) { gallery += '<img width="250" height="250" src="' + images[i].src + '" title="' + images[i].title + '" />'; } 回答1: You can use the replace() method to escape the double quotes: for (var i = 0; i < images.length; ++i) { gallery += '<img width="250" height="250" src="' + images[i].src + '" title="' + images[i].title.replace(/\"/g, '\\"') + '" />'; } The result