我有一个带有javascript代码的播放模板。一切正常但有两个缺点:
setInterval()
另一方面,我对他的解决方案的优势是:
public/javascript
文件夹欢迎任何改进代码的建议!感谢
@(categories: List[WikiCategory])
@import play.i18n._
@import helper._
@main(Messages.get("frontend.wiki.title")) {
<form class="form-search">
<input type="text" class="input-medium search-query" placeholder="@Messages.get("frontend.wiki.search.placeholder")" id="searchInput"></input>
<button type="button" class="btn btn-primary" id="searchButton" onclick="search()">@Messages.get("frontend.wiki.search")</button>
</form>
@* most read articles *@
<div class="row">
@components.wikitable(Messages.get("frontend.wiki.mostread"), WikiArticle.findAllMostReadArticles(5), 999)
</div>
@* articles by category *@
@for((category, i) <- categories.zipWithIndex) {
@if(i%2 == 0) { <div class="row"> }
<div class="span6">
@components.wikitable(category.name, WikiArticle.findAllByCategory(category, 5), category.id)
</div>
@if(i%2 == 1) { </div> }
}
<script type="text/javascript">
var search = function() {
var input = $('#searchInput').val();
$.post( "/wiki/search/" + escape(input), function( data ) {
console.log("found in table999 " + data.length + " articles for criteria " + input);
$('#table999').empty();
$('#table999').append($(template(data)));
});
@for((category, i) <- categories.zipWithIndex) {
$.post( "/wiki/search/@category.id/" + escape(input), function( data ) {
console.log("found in table@category.id " + data.length + " articles for criteria " + input);
$('#table@category.id').empty();
$('#table@category.id').append($(template(data)));
});
}
}
var template = function(articles) {
var table = "";
for (var i = 0, limit = articles.length; i < limit; i++) {
table += article(articles[i]);
}
return table;
}
var shortArticleText = function(text) {
var lengthText = 80
if (text.length > lengthText)
return text.substring(0, lengthText) + "..."
else
return text
}
var article = function(article) {
var row = "<tr><td><a href=\"/wikiarticle/" + article.id + "\" class=\"btn btn-primary\">" + article.title + "</a> </td>";
row += "<td>" + shortArticleText(article.text) + "</td></tr>";
return row;
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
search();
clearInterval(readyStateCheckInterval);
}
}, 10);
</script>
}
答案 0 :(得分:0)
正确实现JS的最佳方法是...在浏览器中检查HTML代码,很可能你在doc的末尾包含jQuery,因此它不可用。创建稳定的HTML文件并在那里使用JS,当你调试并完成它然后将它移动到视图(将部件放在适当的位置)。
还要考虑将JS脚本移动到单独的.js
文件中。