您的位置:首页 > Web前端 > JQuery

[前端] jquery不常用方法测试

2015-06-05 17:07 791 查看
一、$.unique()函数用于根据元素在文档中出现的先后顺序对DOM元素数组进行排序,并移除重复的元素。

var arr = new Array(1, 2, 3, 3, 5, 7);
console.log(arr); // [1, 2, 3, 3, 5, 7]
console.log($.unique(arr)); // [1, 2, 3, 5, 7]


二、select() 选中input框或textarea内容时触发

// <input value="hello" type="text" />
$('input').select(function() {
    alert($(this).val());  // 选中hello时,输出hello
});


三、on(event, element, data, func) 监听事件

// 这样写法的好处是对后来生成的元素也有效
$('body').on('click', 'button.add', {'name': 'tom', 'age': 24}, function(e) {
    console.log(e.data);  // {'name': 'tom', 'age': 24} 返回一个json对象
});

// 监听新方法如所有的touch事件和监听输入事件,实时获取输入的值
$('input').on('input', function() {
    console.log($(this).val());
});


四、:not()过滤器和not()方法的使用

$('input:not(:first)');  // 可以使用过滤选择器
$('input:not([type=text])');  // 可以使用css选择器

$('input').not($('.text2')).click(function() {  // 可以使用jquery方法
   alert(1);
});
$('input').not('.text2').click(function() {   // 可以使用css选择器
   alert(1);
});


五、prop() 函数用于设置或返回当前jQuery对象所匹配的元素的属性值

prop(name, value) — prop是property属性的缩写

获取属性值 prop(name)

设置属性值 prop(name, value)

如果使用prop()函数操作表单元素的checked、selected、disabled等属性,如果该元素被选中(或禁用),则返回true,否则(意即HTML中没有该属性)返回false。

// 读取
document.writeln( $n2.prop("id") ); // n2
// 设置
$n2.prop( { 
    prop_b: "baike",
    prop_c: 18,
    site: { name: "CodePlayer", url: "http://www.365mini.com/" }
} );

// 反选所有的复选框(没选中的改为选中,选中的改为取消选中)
$("input:checkbox").prop("checked", function(index, oldValue){
    return !oldValue;
});


六、$.parseXML()函数用于将字符串解析为对应的XML文档

var xmlStr = '<?xml version="1.0" encoding="UTF-8"?>';
xmlStr += '<user>';
xmlStr += '<username>CodePlayer</username>';
xmlStr += '<age>18</age>';
xmlStr += '</user>';

var xmlDoc = $.parseXML( xmlStr );
$xml = $( xmlDoc );

// 输出到控制台方法
function w(str) {
    console.log(str);
}

var username = $xml.find("username").text();
w( username ); // CodePlayer

var $age = $xml.find("age");
w( $age.text() ); // 18

$age.text("20");
w( $age.text() ); // 20


七、parseJson(json字符)

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );


八、serialize() 序列表表格内容为字符串




form表单:

<form>
        <fieldset>
            <legend>用户信息</legend>
            <input type="text" name="username"><br>
            <input type="radio" name="gender"> 男  <input type="radio" name="gender"> 女
        </fieldset>
        <button type="button">提交</button>
    </form>


JS脚本:

<script> 
        $(function() {
            $('button').click(function() {
                $('.result').append($('form').serialize());
            });
        });
    </script>


提示:

jquery 不仅有serialize()序列化内容为字符串,还有serializeArray() 序列化内容为对象数组(由名/值对组成),具体用哪个看需求

其实需要测试的还有很多,后面会接着更新。

谢谢关注!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: