Javascript代码中不要包含HTML:
var div = document.getElementById("my-div"); div.innerHTML = "<h3>Error</h3><p>Invalid e-mail address.</p>";
在Javascript代码中完全隔绝HTML很难,这一点可以根据实际情况来权衡使用。Javascript 模版技术就是一种有效隔离HTML和Javascript代码的手段,如下是jQuery Template的用法:
// HTML<script id="bookTemplate" type="text/x-jQuery-tmpl"> <div> <img src="BookPictures/${picture}" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script>// Javascript// Create an array of booksvar books = [{ title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" }];// Render the books using the template$("#bookTemplate").tmpl(books).appendTo("#bookContainer"); function formatPrice(price) { return "$" + price.toFixed(2); }
时间: 2024-12-14 03:00:44