/* 说明
引入jquery.js , mobanTmpl.js
该方法取的是id为moban-date 的第一个字节点作为模版,遍历数据。
需要遍历的节点在外面嵌套一个div:
参数形式{xxxx}
{href} : 访问url
{full_tilte} : 完整title
{title} : 截字后的title
{publish_time} :发布时间
方法说明
setMobanDate
setMobanDate('id', title_length,'dataType',num,startIndex);
id : 父节点id,如ul
title_length: title截字长度
dataType: 日期格式
num: 条数
startIndex : 开始位置 0 是第一条
*/
function setMobanDate(id,title_length,dataType,num,startIndex,url){
var tmpl = $('#' +id ).children(':first').html();
//console.log(tmpl);
$.ajax({
url :'http://app.dg.gov.cn/u/app/getHtml',
type : "post",
data : {
url : url?url: 'http://webtest.dg.gov.cn/cndg/dgNews/moban.shtml'
},
dataType : "jsonp",
jsonp : "callback",
jsonpCallback : ('jsonp_' + Math.random()).replace(".", ""),
success : function(dataJ) {
//console.log(data);
var result = dataJ.html;
result = result.replace(/href="/g,'href="http://www.dg.gov.cn');
//console.log(result);
var data = $('');
data.html(result);
data.children('li').each(function(i){
if(startIndex && i=startIndex+num)
return;
if(!startIndex && num && i>=num)
return;
var clone = tmpl;
var title = $(this).find('a:first').html();
//console.log($(this).find('a:first').attr('href'));
var url2 = $(this).find('a:first').attr('href');
var date = $(this).find('span:first').html()
var date2 = formatDate(date,dataType?dataType:"yyyy-MM-dd hh:mm:ss");
if(title.length >= title_length) {
clone = clone.replace("{title}",title.substring(0,title_length) + '..');
}else{
clone = clone.replace("{title}",title);
}
clone = clone.replace("{publish_time}",date2).replace("{full_title}",title).replace("{href}",url2);
$('#' +id ).append(clone);
});
}
});
}
function formatDate(date, fmt)
{
date = date.trim();
fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
var obj =
{
'y': date.substring(0,4), // 年份,注意必须用getFullYear
'M': date.substring(5,7), // 月份,注意是从0-11
'd': date.substring(8,10), // 日期
'H': date.substring(11,13), //
'h': date.substring(11,13),
'm': date.substring(14,16),// 分钟
's': date.substring(17,19)
};
var week = ['天', '一', '二', '三', '四', '五', '六'];
for(var i in obj)
{
fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m)
{
var val = obj[i] ;
//console.log('i:' + i + '||obj.i:'+ obj[i]);
for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
//console.log(val);
return m.length == 1 ? val : val.substring(val.length - m.length);
});
}
return fmt;
}
String.prototype.trim=function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim=function(){
return this.replace(/(^\s*)/g,"");
}
String.prototype.rtrim=function(){
return this.replace(/(\s*$)/g,"");
}