我正在使用.append列出6篇文章(见下文),并希望根据输出中的哪个迭代更改它们使用的网格大小。我把它设置为var grid ='x'。我希望这可以改变,这取决于文章是什么孩子的ul#news。
使用下面的代码,每篇文章都默认为< li class =“sm-12 m-3 cls”>
我相信我正在做的事情是正确的,但有些事情是行不通的。有人可以帮忙吗?
非常感谢!
$user_id = $this->session->userdata("user_id");
$user_type = $this->session->userdata("user_type");
//$column = array('U.type','S.school_name','U.mobile','U.email','U.birthdate','U.anniversary','U.gender','U.firstname','U.lastname');
$this->db->select(*);
$this->db->from('users as U');
$this->db->join('school_user as SU', 'SU.user_id = U.id');
# added where clause
$this->db->where('school.id = SU.school_id OR school.s2m_admin_id = U.id');
$this->db->having('U.status','active');
$this->db->like('U.type', $term);
$this->db->or_like('U.mobile', $term);
$this->db->or_like('U.firstname', $term);
当前输出
for (var i = 0; i < data.response.total; i++) {
if ('ul#news li:nth-child(0)') {
var grid = "sm-12";
} else if ('ul#news li:nth-child(1)') {
var grid = "sm-12 m-6";
} else {
var grid = "sm-12 m-3";
};
var thumbnail = data.response.results[i].blocks.main.bodyHtml;
var title = data.response.results[i].webTitle;
$('ul#news').append('<li class="' + grid + ' cls">' + thumbnail + '<h2>' + title + '</h2></li>');
};
我希望实现的目标
<ul id="events" >
<li class="sm-12 m-3 cls"></li>
<li class="sm-12 m-3 cls"></li>
<li class="sm-12 m-3 cls"></li>
<li class="sm-12 m-3 cls"></li>
<li class="sm-12 m-3 cls"></li>
<li class="sm-12 m-3 cls"></li>
</ul>
答案 0 :(得分:1)
if
条件下的选择器缺少jQuery构造函数$()
,您似乎也假设该元素已经在ul>
中,但它还没有,所以你需要计算它里面的东西。所以你的代码应该是这样的:
for (var i = 0; i < data.response.total; i++) {
if ($('ul#news li').length == 0) { // currently empty, first element going to be inserted
var grid = "sm-12";
} else if ($('ul#news li').length == 1) { // second element going to be inserted
var grid = "sm-12 m-6";
} else {
var grid = "sm-12 m-3";
};
var thumbnail = data.response.results[i].blocks.main.bodyHtml;
var title = data.response.results[i].webTitle;
$('ul#news').append('<li class="' + grid + ' cls">' + thumbnail + '<h2>' + title + '</h2></li>');
};