js/json 数组的操作


JavaScriptSerializer jss = new JavaScriptSerializer(); if (result.ProductJson!=null && result.ProductJson.Any()) { ViewBag.ProductJson = jss.Deserialize<List<ProductJson>>(result.ProductJson); }
          
        <tr>
            <td>设置推荐商品:</td>
            <td>
                <div id="tbbox">
                    <label style="width: 200px; line-height: 30px; text-align: center">商品id</label>
                    <label style="width: 200px; line-height: 30px; text-align: center">排序</label>
                    <p style="width: 550px">
                        <input type="text" style="width: 200px; text-align: center;margin-left:3px" id="ProductId" /><input type="text" style="width: 200px; text-align: center;margin-left:20px" id="SordId" />
                        <input type="button" value="添加" class="operatetxt" style="width: 50px;" onclick=" addtr($.trim($('#ProductId').val()), $.trim($('#SordId').val()))" id="addbtn"/> 
                        <input type="hidden" value="@Model.ProductJson" id="productjson"/>
                    </p>
                    <table id="activetab">
                        <tbody>
                            @if (result != null && ViewBag.ProductJson != null && ViewBag.ProductJson.Count > 0)
                            {

                                foreach (var item in ViewBag.ProductJson)
                                {
                                    var trId = "tr_" + item.sortindex;
                                <tr id="@trId">
                                    <td style='width: 500px; border: none'>
                                        <input type='text' style='width: 200px; text-align: center' value='@item.productid' name='productId'/>
                                        <input type='text' style='width: 200px; text-align: center;margin-left:20px' value='@item.sortindex' name='sordId'/>
                                        <a class='operatetxt' style='width: 40px;' onclick=' deltr(this); '>删除</a></td>
                                </tr>
                                }
                            }
                        </tbody>
                    </table>
                </div>
            </td>
        </tr>
 

 

 <tr>
            <td>状态:</td>
            <td>
                @{
                    var selectTrue = "checked='checked'";
                    var selectFalse = "";
                    if (Model.Enable != null)
                    {
                        if (Model.Enable == true)
                        {
                            selectTrue = "checked='checked'";
                            selectFalse = "";
                        }
                        else
                        {
                            selectTrue = "";
                            selectFalse = "checked='checked'";
                        }

                    }
                }
                <input @selectTrue type="radio" name="IsEnable" value="true" style="width: 20px;cursor:pointer" id="rd1"/><label for="rd1" style="width: 100px; text-align: left; margin-left: 0; cursor: pointer">启用</label>
                <input @selectFalse type="radio" name="IsEnable" value="false" style="width: 20px;cursor:pointer" id="rd2"/><label for="rd2" style="width: 100px; text-align: left; margin-left: 0; cursor: pointer">禁用</label>
            </td>
        </tr>
<script type="text/javascript">
    var productJsonListstr = $.trim($("#productjson").val()); //获取productjson字符串  
    var productJsonList = productJsonListstr.length > 0 ? JSON.parse(productJsonListstr) : new Array(); //由JSON字符串转换为JSON对象
    $(function() {
        $("#KeyWordType").val(@Model.KeyWordType); //控制下拉框选项的值被选中 
        if (productJsonList.length > 0) {
            $('#addtojson').css("display", "none");
        } 
        $("#KeyWord").keyup(function() {
            if ($(this).val().length > 0) {
                $("#keywordunsee").css("display", "none");
            } 
        });
        $("#txtStartTime").blur(function () {
            if ($(this).val().length > 0) {
                $("#startimeunsee").css("display", "none");
               
            }  
        });
        $("#txtEndTime").blur(function () {
            if ($(this).val().length > 0) {
                $("#endtimeunsee").css("display", "none");
            }
        }); 
    });

    //格式化开始时间与结束时间,开始时间小于结束时间
    function dateFmt(obj, type) {
        if (type == 1) {
            if (obj.value == "") {
                WdatePicker({ dateFmt: 'yyyy-MM-dd 00:00:00', maxDate: '#F{$dp.$D(\'txtEndTime\',{s:-1})}' });
            } else {
                WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss', maxDate: '#F{$dp.$D(\'txtEndTime\',{s:-1})}' });
            }
        } else {
            if (obj.value == "") {
                WdatePicker({ dateFmt: 'yyyy-MM-dd 23:59:59', minDate: '#F{$dp.$D(\'txtStartTime\',{d:0})}' });
            } else {
                WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss', minDate: '#F{$dp.$D(\'txtStartTime\',{d:0})}' });
            }
        }

    }

    //用英文逗号替换英文分号、中英文逗号或者回车
    function ReplaceSeperator(mobiles) {
        var i;
        var result = "";
        var c;
        for (i = 0; i < mobiles.length; i++) {
            c = mobiles.substr(i, 1);
            if (c == ";" || c == "," || c == "," || c == "\n")
                result = result + ",";
            else if (c != "\r")
                result = result + c;
        }
        return result;
    }

    //json对象数组按对象属性排序  
    function JsonSort(obj, field, sortby) {
        this.obj = obj;
        this.field = field;
        this.sortby = sortby;
    } 
 
    JsonSort.prototype.sort = function () {
        var $this = this;
        var ascend = function (a, b) {
            return parseInt(a[$this.field]) > parseInt(b[$this.field]) ? 1 : -1;
        };
        var descend = function (a, b) {
            return parseInt(a[$this.field]) > parseInt(b[$this.field]) ? -1 : 1;
        };
        if (this.sortby == "ascend") {
            this.obj.sort(ascend);
        } else {
            this.obj.sort(descend);
        }
    };

    //移除当前的排序商品
    function deltr(clickTd) {
        var tr = $(clickTd).parent();
        var productId = tr.find('input[name=productId]').val();
        var sordId = tr.find('input[name=sordId]').val();
        //alert($.trim(JSON.stringify(productJsonList))); 
        for (var i = 0; i < productJsonList.length; i++) {
            if (productJsonList[i].productid == productId) {
                productJsonList.splice(i, 1); //移除json数组中的该对象
            }
        }
        //alert($.trim(JSON.stringify(productJsonList)));
        tr.remove();
        $('#ProductId').attr("disabled",false);
        $('#SordId').attr("disabled", false);
        $('#addbtn').attr("disabled", false);
    }

    function distincttip() {
        var productId = $.trim($('#ProductId').val());
        var sordId = $.trim($('#SordId').val());
        for (var i = 0; i < productJsonList.length; i++) {
            if ((productId == productJsonList[i].productid)) {
                alert("该商品id已设置");
                return false;
            }
            if (sordId == productJsonList[i].sortindex) {
                alert("该排序id已存在");
                return false;
            }
        }
        return true;
    }

    function showProductList() {
        $('#activetab').html(""); //清空 
        var str = "";
        for (var i = 0; i < productJsonList.length; i++) {
            var trId = "tr_" + productJsonList[i].sortindex;
            str += "<tr id = '" + trId + "'><td style='width:500px;border:none'><input type='text' style='width: 200px; text-align: center' value='" + productJsonList[i].productid + "' name='productId' disabled='disabled'/><input type='text' style='width: 200px; text-align: center;margin-left:20px' value='" + productJsonList[i].sortindex + "' name='sordId' disabled='disabled'/><a class='operatetxt' style='width: 40px;margin-left:20px' onclick=' deltr(this);'>删除</a></td></tr>";
        }
        $("#activetab").append(str);
        //alert($('#activetab').html());
    }

    //添加新的排序商品
    function addtr(productId, sordId) {
        if (productId == '' || productId == undefined) {
            alert("请填写产品id");
            return false;
        }
        if (sordId == '' || sordId == undefined) {
            alert("请填写排序id");
            return false;
        }
        if (sordId > 10 || sordId < 1) {
            alert("请输入在1到10之间的正整数");
            return false;
        }
  
        if (distincttip()) {
            productJsonList.push({ "productid": productId, "sortindex": sordId });
            $('#ProductId').val("");  //清空输入框的值
            $('#SordId').val("");
            var jsonSort = new JsonSort(productJsonList, 'sortindex', 'ascend');
            jsonSort.sort();
            //alert($.trim(JSON.stringify(productJsonList)));
            showProductList();
            if (productJsonList.length == 10) {     //达到10个商品后不可添加
                $('#ProductId').attr("disabled", "disabled");
                $('#SordId').attr("disabled", "disabled");
                $('#addbtn').attr("disabled", "disabled"); 
            }
            if (productJsonList.length > 0 ) {
                $('#addtojson').css("display", "none"); 
            }
        }
    }

    function necessaryinput() {
        var presavejA = $.trim(JSON.stringify(productJsonList));
        if ($("#KeyWord").val() == '' || $("#KeyWord").val() == undefined) {
            alert("请填写匹配的数据");
            return false;
        }
        if ($("#txtStartTime").val() == '' || $("#txtStartTime").val() == undefined) {
            alert("请选择有效期开始时间");
            return false;
        }
        if ($("#txtEndTime").val() == '' || $("#txtEndTime").val() == undefined) {
            alert("请选择有效期结束时间");
            return false;
        }

        if (presavejA == "[]") {
            alert("请设置推荐商品");
            return false;
        }
        return true;
    }
    if ($("#hdId").val() > 0) {
        //更新时不让更改关键字类型与关键字
        $("#KeyWordType").attr("disabled", "disabled").attr("style", "width:200px;background-color:#ddd");
        $("#KeyWord").attr("disabled", "disabled");
    }
    var model = {};

    $("#btnSave").click(function () {
        model.Id = $.trim($("#hdId").val());
        model.KeyWordType = $("#KeyWordType").val();
        model.KeyWord = ReplaceSeperator($.trim($("#KeyWord").val())); 
        model.StartTime = $.trim($("#txtStartTime").val());
        model.EndTime = $.trim($("#txtEndTime").val());
        model.Enable = $("input[name='IsEnable']:checked").val();
        model.ProductJson = $.trim(JSON.stringify(productJsonList));
        if (confirm("你确定保存吗?")) {
            if (necessaryinput()) {
                $.ajax({
                    url: '@Url.Action("EditSortProdutDetail", "SortProduct")',
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(model),
                    success: function (result) {
                        if (result.DoFlag) {
                            alert(result.DoResult);
                            window.location.href = '@Url.Action("Index", "SortProduct", new { id = @Model.Id })';
                        } else {
                            alert(result.DoResult);
                        }
                    }
                });
            }
        }
    });

    $("#btnSaveReset").click(function () {
        model.Id = $.trim($("#hdId").val());
        model.KeyWordType = $("#KeyWordType").val();
        model.KeyWord = ReplaceSeperator($.trim($("#KeyWord").val()));
        model.StartTime = $.trim($("#txtStartTime").val());
        model.EndTime = $.trim($("#txtEndTime").val());
        model.Enable = $("input[name='IsEnable']:checked").val();
        model.ProductJson = $.trim(JSON.stringify(productJsonList));
        if (confirm("你确定保存吗?")) {
            if (necessaryinput()) {
                $.ajax({
                    url: '@Url.Action("EditSortProdutDetail", "SortProduct")',
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(model),
                    success: function (result) {
                        if (result.DoFlag) {
                            alert(result.DoResult);
                            window.location.href = '/SortProduct/EditDetail';
                        } else {
                            alert(result.DoResult);
                        }
                    }
                });
            }

        }
    });

</script>

 


js判断某个元素是否已经在数组中存在

方法一:$.inArray()

$.inArray是jquery中的方法,改方法会返回一个Number指明要找的元素在数组中的index,如果没有,则返回-1。该方法包含三个参数。

$.inArray(value,array,fromIndex)

方法二:遍历数组

遍历数组,如果当前元素与数组中的某个元素相匹配,则说明这个元素已经存在于数组中了。反之证明不存在。

 

参考:https://www.cnblogs.com/Dengxiaobo/p/8138209.html

posted @ 2016-02-05 17:16  BloggerSb  阅读(362)  评论(0)    收藏  举报