我有一个以下HTML结构,它是一个模式弹出窗口,如下所示:
<!-- Left side of the pop up-->
<div class="pop-state">
<!-- state -->
<?php foreach ($users as $user) { ?>
<div class="pop-first-btn">
<a class="check-user" value="<?=$user['id']?>"><?=$user['username']?></a>
</div>
<?php } ?>
</div>
<!-- Right side of the modal popup-->
<div class="pop-brands" >
<?php for ($i = 0; $i < count($brandList); $i++) { ?>
<div class="pop-city-co" id="brands">
<label>
<input class="check-city" type="checkbox" name="" value="<?=$brandList[$i]['id']?>" data-id="<?=$i ?>"><?=$brandList[$i]['name']?>
</label>
</div>
<?php } ?>
</div>
当用户点击链接时,我会执行以下jQuery事件:
$('.check-user').click(function() {
var user_id = $(this).attr('value');
$.post("/user/usersBrands", {userId:user_id}, function(data){
//console.log(data);
var brands = $('<div />').append(data).find('#brands').html();
$('#brands').html(brands);
console.log(brands);
});
});
我拿起userId,将它发送到我的函数,然后我想用我的弹出窗口右侧更新用户列表,以复选框列表的形式......这就是我的功能我打电话给:
public function usersBrandsAction(){
$userId = $this->getRequest()->getPost("userId");
if(!empty($userId))
{
$brandList = $this->getBrandModel()->brandList();
$this->dieCustomCode($brandList); // it can be echo instead of this or anything that would return me the array of brands...
}
}
所以,当我点击链接时,没有任何显示......控制台说#brands由于某种原因未定义...有人可以帮我解决这个问题吗? :/
答案 0 :(得分:1)
1)我建议您使用append()
代替html()
,直到您确实需要使用.html()
方法替换所有以前的数据。
所以,而不是
$('#brands').html(brands);
使用
$('#brands').append(brands);
此外,而不是:
var brands = $('<div />').append(data).find('#brands').html();
写:
var brands = $('<div />').append(data);
因为,一旦将数据附加到DIV元素,就不再需要遍历DOM了。
2)确保您没有重复使用id&#34;品牌&#34;在DOM中。
3)检查您的"#brands"
或".pop-city-co"
是否未被CSS隐藏。
4)我还建议在PHP端使用json_encode
,然后在客户端解析它。
答案 1 :(得分:0)
尝试像这样使用。它可能会奏效。
$('.check-user').click(function(e) {
e.preventDefault();
var user_id = $(this).attr('value');
$.post("/user/usersBrands", {userId:user_id}, function(data){
//console.log(data);
var brands = "<div>" + data + "</div>";
$('#brands').html(brands);
console.log(brands);
});
});
答案 2 :(得分:0)
我不太了解JS,但是一旦我尝试了这个并为我工作。
只需将参数名称放在引号&#39; userId&#39;
中我发布此答案是因为我的声誉不允许我发表评论