开发者社区> 问答> 正文

点击把字符串添加到数组,再点击从数组删除

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style>
.yx LI{ float:left;  margin-right:80px}
</style>
<body>
<p style="height:120px;"></p>
<ul class="yx" style=" border:1px solid #06F;height:80px;"></ul>
<ul class="list">
    <li><input name="" type="checkbox" value="" />111111111</li>
    <li><input name="" type="checkbox" value="" />22222222222</li>
    <li><input name="" type="checkbox" value="" />33333333333</li>
</ul>
<input class="tj" type="button" value="添加"/>
</body>
<script>
 
$('.list li input').each(function(i) {
    text  = [];
    $(this).click(function(){   
        if ($(this).is(":checked"))  {
            text.push($(this).parent('li').text())
        }else{
            text.splice($(this),1)
        };
        $('p').text(text)
    }); 
});
 
$('.tj').click(function(){
    $('.yx').html("<input type='checkbox' value='' />"+text+"")
})
 
 
</script>
</html>

展开
收起
a123456678 2016-07-11 16:47:45 2311 0
1 条回答
写回答
取消 提交回答
  • text.splice($(this), 1); //这行代码参数错了
    /*
     Array.prototype.splice(start,deleteCount,val1,val2,...):从start位置开始删除deleteCount项,并从该位置起插入val1,val2,... 
     */
    var text = [];
    $("ul.list").on("click", ":checkbox", function () {
        var el = $(this);
        if (el.is(":checked")) {
            text.push(el.parent("li").text());
            el.data("index", text.length - 1);  //保存索引
        } else {
            text.splice(el.data("index"), 1);  //删除数组下, 本元素索引对应的值
        }
     
        $("p").text(text);
    });
    2019-07-17 19:54:22
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载