我遇到以下javascript问题,
<script type='text/javascript'>
var $OriginalImage = 'http://4.bp.blogspot.com/-SUwv0x4nozI/UjBwsjK1AGI/AAAAAAAAZAI/HgfzndxJ_Nk/s1600/Android+Wallpaper.jpg';
var $thumbnail = $OriginalImage.replace('s1600','s320');
document.write = '<img alt='Android Monochrome Wallpaper' class='img-responsive img-hover' src=' +$thumbnail+ '/>';
</script>
控制台中的错误。
我已尝试将document.write();
标记转义但它没有工作......如何解决此问题?
答案 0 :(得分:1)
以下是正确转义的结果:
<script type='text/javascript'>
var OriginalImage = 'http://4.bp.blogspot.com/-SUwv0x4nozI/UjBwsjK1AGI/AAAAAAAAZAI/HgfzndxJ_Nk/s1600/Android+Wallpaper.jpg';
var thumbnail = OriginalImage.replace('s1600','s320');
document.write('<img alt="Android Monochrome Wallpaper" class="img-responsive img-hover" src="' +thumbnail+ '"/>');
</script>
但正如@limelights在评论中所说,而不是document.write,请转到appendChild
var OriginalImage = 'http://4.bp.blogspot.com/-SUwv0x4nozI/UjBwsjK1AGI/AAAAAAAAZAI/HgfzndxJ_Nk/s1600/Android+Wallpaper.jpg';
var thumbnail = OriginalImage.replace('s1600', 's320');
var DOM_img = document.createElement("img");
DOM_img.alt = "Android Monochrome Wallpaper";
DOM_img.class = "img-responsive img-hover"
DOM_img.src = thumbnail;
document.body.appendChild(DOM_img);
或使用setAttribute:
var OriginalImage = 'http://4.bp.blogspot.com/-SUwv0x4nozI/UjBwsjK1AGI/AAAAAAAAZAI/HgfzndxJ_Nk/s1600/Android+Wallpaper.jpg';
var thumbnail = OriginalImage.replace('s1600', 's320');
var elem = document.createElement("img");
elem.setAttribute("src", thumbnail);
elem.setAttribute("class", "img-responsive img-hover");
elem.setAttribute("alt", "Android Monochrome Wallpaper");
document.body.appendChild(elem);
附加到锚标记:
var OriginalImage = 'http://4.bp.blogspot.com/-SUwv0x4nozI/UjBwsjK1AGI/AAAAAAAAZAI/HgfzndxJ_Nk/s1600/Android+Wallpaper.jpg';
var thumbnail = OriginalImage.replace('s1600', 's320');
var elem = document.createElement("img");
elem.setAttribute("src", thumbnail);
elem.setAttribute("class", "img-responsive img-hover");
elem.setAttribute("alt", "Android Monochrome Wallpaper");
document.getElementById('addImage').appendChild(elem);
<a href="example.html" id="addImage"></a>
或没有ID:
var OriginalImage = 'http://4.bp.blogspot.com/-SUwv0x4nozI/UjBwsjK1AGI/AAAAAAAAZAI/HgfzndxJ_Nk/s1600/Android+Wallpaper.jpg';
var thumbnail = OriginalImage.replace('s1600', 's320');
var elem = document.createElement("img");
elem.setAttribute("src", thumbnail);
elem.setAttribute("class", "img-responsive img-hover");
elem.setAttribute("alt", "Android Monochrome Wallpaper");
document.getElementsByTagName("a")[0].appendChild(elem);
<a href="example.html"></a>