jQuery随记汇总

1.jQuery操作行内样式style中的某一项的值:>>

<div id="test" style=" display:none;">
</div>

$("#id").css(""background-color","#8f93a2");

 

2.jQuery中json对象与json字符串互换

json字符串转json对象:jQuery.parseJSON(jsonStr);
json对象转json字符串:JSON.stringify(jsonObj);

IE中可能对unicode使用“\uXXXX”格式来编码,可以使用如下来解码:

function unicode2Char(str) {
  return (str.replace(/\\/g, "%"));
}

 

3. jQuery判断获取的对象是否存在:

错误写法:

if($("#someID")) //写法是错误的,因为jQuery对象永远都有返回值

正确写法:

var obj = $('#id');
if(obj.length > 0)
{
  alert('对象存在');
}
//或者以下方式:
if(obj[0])
{
  alert('对象存在');
}

 

4.根据输入值和下拉框变化计算总价格:

<script src="~/Content/plugins/layer/layer.js"></script>
    <script type="text/javascript">
        $(function () {
            //填写学时数执行
            $("#hourCount").keyup(function () {
                //判断输入的是否是数字
                var inputText = $(this).val();
                if (inputText == '') {
                    return;
                }

                if (isNum(inputText)) {
                    getTotalPrice();
                }
                else
                {
                    $('#totalPrice').text('');
                }
            });
            //选择科目下拉改变执行
            $("#subjectSelect").change(function () {
                getTotalPrice();
            });

        });

        //计算预约总价格
        function getTotalPrice() {
            var subjectPrice = $("#sel-driving").find("option:selected").val();
            var hourCount = $('#hourCount').val();
            var totalPrice = subjectPrice * hourCount;
            $('#totalPrice').text("¥" + totalPrice);
        }

        //判断是否全是整数
        function isNum(str) {
            var ex = /^\d+$/;
            if (ex.test(str)) {
                return true;
            }
            layer.msg('请输入数字!');
            return false;
        }
    </script>

 <div class="km">
            <select id="subjectSelect"><option id="subject2" value="@Model.Subject2Price">科目二</option><option id="subject3" value="@Model.Subject3Price">科目三</option></select>
        </div>
        <div class="text-Num">
            <input id="hourCount" type="text" name="num" value="@(Model.LeastBuyHourCount!=null?Model.LeastBuyHourCount:1)">个学时
        </div>
        <div class="btnSubmit">
            <div><span id="totalPrice"></span>预约</div>
        </div>

 

5.获取子窗体window对象:

var childWindow = $("#editFrame")[0].contentWindow;
childWindow.subEditForm();

 

6.子窗体怎样调用父窗体的方法

function afterEdit() {
    //子窗体怎样调用父窗体的方法
    window.parent.afterEdit();
}

 

7.时间选择插件下载(带时分):

去下载>>

 

8.多个元素同一个事件,执行同样的动作:

//更改审核状态和类型加载页面数据
$('#StatusSelect,#TypeSelect').on("change", function () {
    status = $("#StatusSelect").val();
    type = $("#TypeSelect").val();
    LoadPageList(status, type, pageIndex, pageSize);
}); 

 

9.Jqury的String.format()自定义方法:

        //自定义字符串格式化函数,用法:"{0}----{1}".format("xx","yy");
        String.prototype.format = function () {
            var result = this;
            if (arguments.length == 0)
                return null;
            for (var i = 0; i < arguments.length; i++) {
                var re = new RegExp('\\{' + (i) + '\\}', 'gm');
                result = result.replace(re, arguments[i]);
            }
            return result;
        };

 

10.Jquery的Live用法: 详细说明>>

当元素是通过ajax方式(同步或异步)方式,后来返回的,如果想注册事件,用传统方式不行:

$('#id').click(function(){...});

需要这样做:

$('#id').live('click',function(){...});

 

11.jQuery.form的使用方法

 

12.页面回到顶部

$(window).scrollTop(0);

 

13.加载图标提示:

 var layerLoad = layer.load(2); //加载
 layer.close(layerLoad); 关闭加载

 

14.将光标定位到输入框末尾:

var content = $.trim($('#content').val();
$('#content').focus().val(content);

 

15.光标处插入内容,如表情:

<script type="text/javascript">
//光标处插入内容扩展方法
(function ($) {
    $.fn.extend({
        insertAtCaret: function (myValue) {
            var $t = $(this)[0];
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else
                if ($t.selectionStart || $t.selectionStart == '0') {
                    var startPos = $t.selectionStart;
                    var endPos = $t.selectionEnd;
                    var scrollTop = $t.scrollTop;
                    $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                    this.focus();
                    $t.selectionStart = startPos + myValue.length;
                    $t.selectionEnd = startPos + myValue.length;
                    $t.scrollTop = scrollTop;
                } else {
                    this.value += myValue;
                    this.focus();
                }
        }
    })
})(jQuery);

//光标处插入表情,调用
$("#content").insertAtCaret(faceText);
</script>

 

16.复制文本到剪贴板:(亲测不兼容IE浏览器,没卵用)

js插件下载:clipboard(JS复制内容到剪贴板插件).zip

(1)引用:<script type="text/javascript" src="clipboard.min.js"></script

(2)调用示例:

<!--测试2-->  
$(document).ready(function(){    
   var clipboard1 = new Clipboard('.a');   
   clipboard1.on('success', function(e) {  
       console.log(e);  
        alert("测试2复制成功!")  
        });  
   clipboard1.on('error', function(e) {  
               console.log(e);  
               alert("测试2复制失败!请手动复制")  
        });  
})  

详细使用说明>>

 

17.PC端复制插件ZeroClipboard:(含解决IE11高版本不兼容问题) 详细说明>>   参考>>

ZeroClipboard插件下载>>

示例:

<input id="inviteLink" type="text" value="链接地址">
<span id="copy" class="copy" data-clipboard-target="inviteLink">复制链接</span>  //要复制的内容框id

调用:以下代码需要放到</body>下面,否则document.getElementById报错,因为document还没加载完成。

<script src="~/Content/Plugins/layer/layer.js"></script>
<script src="~/Content/Plugins/ZeroClipboard/ZeroClipboard.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#copy').click(function () {
            clipboard();
        })
    });

    function clipboard() {
        //针对IE复制兼容性问题
        if (window.clipboardData) {
            var text = $('#inviteLink').val();
            window.clipboardData.clearData();
            window.clipboardData.setData('text', text);
            layer.msg('已复制');
        }
    }

    // 定义一个新的复制对象
    var clip = new ZeroClipboard(document.getElementById("copy"), {
        moviePath: "/Content/Plugins/ZeroClipboard/ZeroClipboard.swf"
    });
    // 复制内容到剪贴板成功后的操作
    clip.on('complete', function (client, args) {
        layer.msg('已复制');
    });

    clip.on('error', function (client, args) {
        layer.msg('复制失败,请手动复制');
    });
</script>

<style type="text/css">
    .layui-layer {
        border: 0px solid #ccc;
        background-color: black;
        box-shadow: none;
    }
</style>

 

// 定义一个新的复制对象
                var clip = new ZeroClipboard(document.getElementById("copy"), {
                    moviePath: "/Content/Plugins/ZeroClipboard/ZeroClipboard.swf"
                });
                // 复制内容到剪贴板成功后的操作
                clip.on('complete', function (client, args) {
                    layer.msg('已复制');
                });

                clip.on('error', function (client, args) {
                    layer.msg('复制失败,请手动复制');
                });
posted @ 2015-02-02 18:05  IT浪潮之巅  阅读(220)  评论(0编辑  收藏  举报
   友情链接: 淘宝优惠券