53 front-end --jQuery2

1. Properties

attr: id for own custom properties or attributes

.attr({'属性名':'值',...}); // 设置属性
.attr('属性名');       //查看属性
.removeAttr('属性名'); //删除属性

prop: a checkbox and radio

单选框radio:必须定位到具体的标签
.prop('checked');   // 查看标签是否选中,返回true和false
.prop('checked',true);  // 选中
.prop('checked',false); // 取消选中

多选框checkbox:
    $(":checkbox").prop('checked',true) //全选

When set to attr attribute checkbox, no way to deselect.

to sum up:

  1. For the label to see some of the attributes and custom attributes with attr

  2. For returns a Boolean value, such as checkbox, radio and the option of whether it is selected or setting is selected and uncheck all with prop.

True and false attribute has two properties, such as checked, selected or disabled using prop (), others use attr ()

示例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<div>
    用户名:<input type="text">
</div>
<div>
    密码:<input type="password" name="pwd">
</div>
<div class="d1">
    性别:
    <input type="radio" name="sex" id="s1" value="1">男
    <input type="radio" name="sex" id="s2" value="2">女
</div>
<div>
    爱好:
    <input type="checkbox" name="hobby" value="3">抽烟
    <input type="checkbox" name="hobby" value="4">喝酒
    <input type="checkbox" name="hobby" value="5">蹦迪
</div>
</body>
</html>


操作:
$('#d1').attr({'age1':'18','age2':'19'});   // 添加两个属性
$('#d1').attr('age1','18');         // 添加一个属性
$("").prop("checked");
$("#s1").prop("checked");           // 查看 男 是否被选中
$("#s2").prop("checked",true);      // 选择 女

$(":checkbox").prop("checked",true)     // 爱好 全选
$(":checkbox").prop("checked",true)     // 爱好 全取消选中

2. Document Processing

Adding to the back of the interior of the specified element (son) of

$(A).append(B)  // 把B追加到A
$(A).appendTo(B)// 把A追加到B
方式一:
var a = document.createElement('a');
$(a).text('百度');
$(a).attr('href','http://www.baidu.com');
$("#d1").append(a);

方式二:
$('#d1').append("<a href=''>百度</a>")
// 添加a标签,能够识别标签

方式三:
// var s = `<a href="">${xxx}</a>`      // 字符串格式化
var s = '<a href="">' + '百度' + '</a>'
$('#d1').append(s)

Add to specify the elements inside the front (son) of

$(A).prepend(B)     // 把B前置到A
$(A).prependTo(B)   // 把A前置到B

Add the specified element to an external (Brother) behind

$(A).after(B)       // 把B放到A的后面
$(A).insertAfter(B) // 把A放到B的后面

Element added to the specified external front (Brother) of

$(A).before(B)      // 把B放到A的前面
$(A).insertBefore(B)// 把A放到B的前面

Removed and emptied

remove()    // 删除所有匹配的元素。
empty()     // (清空)删除匹配的元素集合中所有的子节点,包括文本被全部删除,但是匹配的元素还在

replace

$(A).replaceWith(B);    //B替换A
$(A).replaceAll(B);     //A替换B

clone

.clone();   // 克隆标签,但没有事件效果
.clone(true);   // 克隆标签,并且克隆事件

Example Cloning;

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

<button class="btn">屠龙宝刀,点击就送!</button>
</body>
<script>
    $(".btn").click(function () {
        // var bEle=$(this).clone();
        var bEle=$(this).clone(true);
        $(this).after(bEle);
    })
</script>
</html>

3. Event

Binding events

方式一:
$("#d1").click(function (){
    $(this).css('background-color','green');
})

方式二:
$("#d1").on('click',function (){
    $(this).css('background-color','green');
})

Delete the event

.off() 方法移除用 .on()绑定的事件处理程序。
   $("li").off("click")

Common events

click(function(){...})  //鼠标左键点击
hover(function(){...})  // 鼠标悬浮
blur(function(){...})   // 失去光标
focus(function(){...})  // 获取到光标
change(function(){...}) //内容发生变化,用于select等
keydown/keyup(function(){...})  //键盘按下/抬起
input       // 实时监听输入值

input event , must be binding on, used for searching, real-time monitoring of input values

$('#cc').on('input',function () {
    console.log($(this).val());
})


绑定多个事件 事件名称空格间隔:
$('#xxx').on('input blur',function () {
     console.log($(this).val());
})

mouseenter event : the mouse enters the tag trigger, trigger only once to enter the sub label does not trigger.

mouseout event : the mouse leaves the trigger tag

hover event : the integration of the two into a top event

Not a native of that hover dom, and there is no onhover js event, this is the jQuery hover event, is jQuery package, there is no native js

 hover事件 鼠标进进出出的事件
 
$('#d1').hover(
    // 鼠标进入
    function () {
        $(this).css('background-color','green');
    },
    // 鼠标离开
    function () {
        $(this).css('background-color','red');
    });

mouseover event : the mouse enters the trigger, enter the sub label will trigger (note the mousenter)

keydown / keyup events: keyboard press / release

$(window).keydown(function (e) {
    console.log(e.keyCode)
})      //按下键就会输出一个值

$(window).keyup(function (e) {
    console.log(e.keyCode)
})      //抬起键就会输出一个值

Event bubbling

Child and parent label label (label ancestors) bound to the same event. For example, a click event, click on the tag, it will trigger up one level of the parent or grandparent of the event.

Solution: Add in sub-tab function in:

​ return false;

Or: e.stopPropagation ();

$('.c1').click(function () {
alert('父级标签!!!');
});
$('.c2').click(function (e) {
alert('子标签~~~');
// 阻止事件冒泡(阻止事件发生)
return false;           // 方式1
// e.stopPropagation()  // 方式2
})

Event delegates

Event delegates is through the principle of event bubbling, using the parent tag to capture the event sub label will come in the future to add some sub-label automatically binding on the event (sub label is dynamic).

# 示例:克隆
$("#d1").on('click','.btn',function () {
    // $(this)是点击的儿子标签
    var a=$(this).clone();
    $("#d1").append(a);
})

// 将儿子.btn 的事件委托给父级#d1,

4. page load

1. window.onload event

将script放在html的head部分:onload 等待页面内容全部加载完之后自动触发事件,多个onload存在覆盖现象
    window.onload = function(){
        $("").click(function () {       
        });
    }

2. jQuery load event

jQuery page execution after loading is complete.

$(document).ready(function(){
// 在这里写JS代码...
})

简写:
$(function () {
    $("").click(function () {       
    });
})

And window.onload difference :

  Before calling 1.window.onload () function has covered the phenomenon, we must wait for the picture to load after the completion of the resource

  2.jQuery this phenomenon entrance function has no cover, after the document has finished loading you can call (recommended to use this function)

示例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <script>
        window.onload = function () {
            $(".c1").click(function(){
                $(this).addClass("cc")
            })
        };
        // window.onload = function () {
        //     $(".c1").click(function(){
        //         $(this).addClass("c2")
        //     })
        // }
        $(function () {
            $(".c2").click(function(){
                $(this).addClass("cc")
            })
        });
    </script>
    <style>
        .c1{
            width: 200px;
            height:200px;
            background-color:red;
        }
        .c2{
            width: 200px;
            height: 200px;
            background-color: green;
        }
        .cc{
            width: 200px;
            height: 200px;
            background-color: blue;
        }
    </style>
</head>
<body>
<div class="c1"></div>
<div class="c2"></div>
</body>

</html>

5. each

A general iterative function, which can be used seamlessly and iterative array of objects. Arrays and array-like objects to a number of iterations indexed by the length of the property (e.g., a function of the parameter object), from 0 to length - 1. Other objects to iterate through the property names.

$----->jQuery.each

# 循环数组: k是索引位置,v是数据
$.each(数组,function (k,v){
    console.log(k,v)
})

# 循环标签:v是Dom标签
    .each() 方法用来迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this 总是指向这个元素。
    
$("li").each(function (k,v) {
    console.log(k,v)                // 取标签
    console.log(k,$(v).text())      // 取标签文本
})



终止each循环:
    return false;
注意:
  在遍历过程中可以使用 return false提前结束each循环。
  而直接使用return;后面什么都不加,不写false,就是跳过本次循环。
数组示例:
var a = [1,3,5,7,9];
$.each(a,function (k,v){
    console.log(k,v)
});
/*
0 1
1 3
2 5
3 7
4 9
*/
标签示例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>each</title>
</head>
<body>
<div>
    <ul>
        <li>aaa</li>
        <li>bbb</li>
        <li>ccc</li>
        <li>ddd</li>
        <li>eee</li>
        <li>fff</li>
    </ul>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</html>

操作:
$("li").each(function (k,v) {
    console.log(k,v)
});     // 查看所有的li标签
$("li").each(function (k,v) {
    console.log(k,$(v).text())
})      // 查看所有的li标签的文本内容

6. animation

.show(3000)         // 3s后显示标签
.hide(2000)         // 2s后隐藏标签
.toggle(3000)       // 以前什么效果,反着来
.slideDown(2000)    // 向下滑动
.slideUp(2000)      // 向上滑动隐藏
.slideToggle()      

// 淡入淡出(控制透明度)
fadeIn([s],[e],[fn])
fadeOut([s],[e],[fn])
fadeTo([[s],o,[e],[fn]])  o参数是透明度,0-1的区间,意思是淡入或者淡出到一个多大的透明读
fadeToggle([s,[e],[fn]])

// 自定义
animate(p,[s],[e],[fn])
$("div").hide(3000,function () {
    alert("执行完毕");
})      // 执行完动画后,执行回调函数

7. data()

The method of any jQuery object data has to be saved at any value, may be used instead of the global variables
to store arbitrary data on all the elements of the set of matched elements or element returns the first matching element in the set given the name the value of the stored data.

 .data (key, value): set value

Description: storing arbitrary data in the matched elements.

$("div").data("k",100);//给所有div标签都保存一个名为k,值为100

.data (key): value, if not return undefined

  Description: Returns the first element in the set of matched elements in value to the data storage name is given - by .data(name, value)or HTML5 data-*property.

$("div").data("k");//返回第一个div标签中保存的"k"的值

.removeData(key):

  Description: Removes data stored on the elements, without key parameter indicates the removal of all stored data.

$("div").removeData("k");  //移除元素上存放k对应的数据

8. Plug

jQuery.extend(object)

 Add new features under the jQuery namespace. Multi-use plug-in for developers to add new functions to the jQuery in.

Shorthand: $ extend ().

Other labels can not be used,

$.extend({
    min:function (a,b) {return a < b ? a : b;},
    max:function (a,b) {return a < v ? a:b;}
})
$.min(2,5)      // 2

$ .Fn.extend () # can be used

$.fn.extend({
    min:function (a,b) {return a < b ? a : b;},
    max:function (a,b) {return a < v ? a:b;}
})
$("#d1").max(2,5)       // 5

Guess you like

Origin www.cnblogs.com/yzm1017/p/11563882.html