几个 js 的代码片段

字符串格式化

/**
 * 字符串格式化
 * 使用方法:
 *  str = format_str( 'abc{0}efg{1}', 'a', 'b'); // 获得:abcaefgb
 */

$.format_str = function ( string ) {
    var args = Array.prototype.slice.call(arguments, 1);
    return string.replace(/{(\d+)}/g, function (match, n) {
        return typeof args[n] != 'undefined' ? args[n] : match;
    });
};

清空表单2

/**
 * 《清空表单2》
 * example:
 *      $('#frmId').clearForm();
 * by Livon 2019-03
 */
$.fn.clear_form = function () {

    $(this).find('input').each(function (i, el) {
        var type = el.type;
        var tag = el.tagName.toLowerCase();
        if (type == 'text' || type == 'password' || type == 'hidden' || tag == 'textarea')
            $(el).val('');
        else if ( ( type == 'checkbox' || type == 'radio' ) && $(el).attr("id") )
            document.getElementById($(el).attr("id")).checked = false;
        else if (tag == 'select')
            $(el).selectedIndex = -1;
            // $(el).val('');
    });
};



给整个表单赋值


/**
 * 给整个表单赋值
 * - - - - - - - - - - - - - - - - - -
 * 使用方法:
 *    $.getJSON(URL,param,function(data){
		alert(data.type);
		$("form").setForm(data);
		... ...
	原文:https://blog.csdn.net/xiaosheng_papa/article/details/41676087
 */
$.fn.setForm = function (jsonValue) {
    var obj = this;
    $.each(jsonValue, function (name, ival) {
        var $oinput = obj.find("input[name=" + name + "]");
        if ($oinput.attr("type") == "radio" || $oinput.attr("type") == "checkbox") {
            $oinput.each(function () {
                if (Object.prototype.toString.apply(ival) == '[object Array]') { // 是复选框,并且是数组
                    for (var i = 0; i < ival.length; i++) {
                        if ($(this).val() == ival[i])
                        // $(this).attr("checked", "checked");
                            document.getElementById($(this).attr("id")).checked = true;
                    }
                } else {
                    if ($(this).val() == ival) {
                        // $(this).attr("checked", "checked");
                        // document.getElementById("chkbox_IS_ACTIVE").checked = true;
                        document.getElementById($(this).attr("id")).checked = true;
                    }
                }
            });
        } else if ($oinput.attr("type") == "textarea") { // 多行文本框
            obj.find("[name=" + name + "]").html(ival);
        } else {
            obj.find("[name=" + name + "]").val(ival);
        }
    });
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值