day57——jQuery操作标签/绑定事件

jQuery标签查找练习题

题目:

  1. 找到本页面中id是i1的标签
  2. 找到本页面中所有的h2标签
  3. 找到本页面中所有的input标签
  4. 找到本页面所有样式类中有c1的标签
  5. 找到本页面所有样式类中有btn-default的标签
  6. 找到本页面所有样式类中有c1的标签和所有h2标签
  7. 找到本页面所有样式类中有c1的标签和id是p3的标签
  8. 找到本页面所有样式类中有c1的标签和所有样式类中有btn的标签
  9. 找到本页面中form标签中的所有input标签
  10. 找到本页面中被包裹在label标签内的input标签
  11. 找到本页面中紧挨在label标签后面的input标签
  12. 找到本页面中id为p2的标签后面所有和它同级的li标签
  13. 找到id值为f1的标签内部的第一个input标签
  14. 找到id值为my-checkbox的标签内部最后一个input标签
  15. 找到id值为my-checkbox的标签内部没有被选中的那个input标签
  16. 找到所有含有input标签的label标签

答案:

# 1
$('#i1')
# 2
$('h2')
# 3
$('input')
# 4
$('.c1')
# 5
$('.btn-default')
# 6
$('.c1,h2')
# 7
$('.c1,#p3')
# 8
$('.c1,.btn')
# 9
$('form input')
# 10
$('label input')
# 11
$('label input:first')
# 12
$('#p2~li')
# 13
$('#f1 input:first')
# 14
$('#my-checkbox input:last')
# 15 
$('#my-checkbox input:[checked!="checked"]')
# 16
$('label:has("input")')

操作标签

  • 操作类

"""
增加、删除、判断、有删无增
jQ:                          js:
.addClass()  				.classList.add()			
.removeClass()               .classLIst.remove()
.hasClass('c1','c2')         .classList.contains()
.toggleClass()               .classList.toggle()
"""

  • css操作

需求:一行代码将第一个p便签变成红色,将第二个p便签变成绿色。

jQuery链式操作

"""
<p>红色</p>
<p>绿色</p>"""

$('p').first().css('color','red').next().css('color','green');

内部原理:jQuery链式操作可以一行代码做到操作很多标签是因为jq对象调用jq方法之后返回的还是当前的jq对象,所以能继续的调用jq对象的其他方法

python代码展示原理

class Myclass(object):
    def func1(self):
        print('func1')
        return self

    def func2(self):
        print('func2')
        return self

    ...
    
    
obj = Myclass()
obj.func1().func2()
"""
func1
func2
"""
  • 位置操作

# 标签相对于浏览器的位置
$('p').offset();

# 相对于父标签的位置
$('p'),opsiton()

# scrollTop()页面上下滚动条当前的值
$(window).scrollTop()  # 未往下滑
# 0
$(window).scrollTop()  # 滑到一定的位置
# 999
$(window).scrollTop(500) # 加了参数就是设置,滚动条跳到设置值的位置

# scrollTop()页面左右滚动条当前的值
$(window).scrollLeft()  # 未往左滑
# 0
$(window).scrollLeft()  # 滑到一定的位置
# 666

  • 获取尺寸

$('p').height()  # 获取文本高度
20
$('p').width()  # 文本宽度
1670
$('p').innerHeight()  # 文本+padding的高度
26
$('p').innerWidth()  # 文本+padding的宽度
1674
$('p').outerHeight()  # 文本+padding+borderg的高度
26
$('p').outerWidth()  # 文本+padding+borderg的宽度度
1674

  • 文本操作

"""
1.操作标签内部文本
	获取文本
	设置文本
2.操作标签内部文本和标签
	获取文本和标签
	设置文本和标签	
jQ:                          js:
text() 				        innerText			
text("666")                  innerText = '666'

html()                       innerHTML
text('<h1>666</h1>')         innerHTML = '<h1>666</h1>'
"""


# 操作示例
"""
<div>
    <p>
       111
    </p>
</div


$('div').html()
"
    <p>
        111
    </p>
"

$('div').text('666')
w.fn.init [div, prevObject: w.fn.init(1)]

$('div').html('666')
w.fn.init [div, prevObject: w.fn.init(1)]

$('div').text('<h1>666</h1>')
w.fn.init [div, prevObject: w.fn.init(1)]

$('div').html('<h1>666</h1>')
w.fn.init [div, prevObject: w.fn.init(1)]
"""

  • 获取值操作

"""
jQ:                           js:
.val()			             .value		
"""


# 操作示例
$('#d1').val()  # 在文本框中输入"刚输入的内容",再获取值
# "刚输入的内容"

$('#d1').val('刚设置的内容')  # 括号内不加参数就是获取,加了就是设置
# 文本框中显示:刚设置的内容

$('#d2').val()  # 只能获取文件的路径
"C:\fakepath\01_测试路由.png"

"""
jq中没有获取文件的方法,
得先将jq对象转成标签对象[0],
再获取文件对象.files,然后获取文件[0]"""
$('#d2')[0].files[0]
"""
File {name: "01_测试路由.png", lastModified: 1557043083000, lastModifiedDate: Sun May 05 2019 15:58:03 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 28733, …}"""
           
  • 属性操作

"""
1.获取属性
2.设置属性
3.删除属性

jQ:                          js:
attr(name) 				    getAttribute()			
attr(name,value)             setAttribute()		
removeAttr(name)             removeAttribute()
"""


# Ps:
"""
在用变量存储对象的时候,推荐使用的命名方式,老套路了,见名知意嘛!
jQ:                          js:
$XXXEle(jQuery对象)		   XXXEle(标签对象)
"""

# 操作示例
let $pEle = $('p')
# undefined
   
$pEle.attr('id')
# "d1"

$pEle.attr('class')
# undefined

$pEle.attr('class','c1')
#w.fn.init [p#d1.c1, prevObject: w.fn.init(1)]

$pEle.attr('id','id666')
#w.fn.init [p#id666.c1, prevObject: w.fn.init(1)]

$pEle.attr('password','5201314')
# w.fn.init [p#id666.c1, prevObject: w.fn.init(1)]

$pEle.removeAttr('password')
w.fn.init [p#id666.c1, prevObject: w.fn.init(1)] 

对于标签上有的能够看到的属性和自定义属性用atrr,而对于返回布尔值的如checkbox、radio、option等是否被选中的时候就应该用prop,再用atrr设置无效无效。

$('#d3').attr('checked','checked')  # 无效
# w.fn.init [input#d3]

$('#d2').prop('checked')  # id为2的默认未选中
# false
$('#d3').prop('checked')  # id为3的默认选中
# true
$('#d2').prop('checked',true)  # 选中
# w.fn.init [input#d3]
$('#d3').prop('checked',false)  # 取消选中
# w.fn.init [input#d3]
  • 文档处理

"""
1.创建标签
2.往标签内部追加子标签
...

jQ:                          js:
$('<p>') 				    createElement('p')		
append()                     appendChild()
...
"""

# 操作示例
let $pEle = $('<p>')
$pEle.text('你好啊 草莓要不要来几个?')
$pEle.attr('id','d3')          
$('#d1').append($pEle) 
$pEle.appendTo($('#d1'))  # 两者等价,内部尾部追加 
           
$('#d1').prepend($pEle)
$pEle.prependTo($('#d1'))  # 两者等价,内部头部追加
         
$('#d2').after($pEle)
$pEle.insertAfter($('#d1'))  # 放在某个标签后面
        
$('#d1').before($pEle)
$pEle.insertBefore($('#d2'))  # 放在某个标签前面

$('#d1').remove()  # 将标签从DOM树中删除标签,  
$('#d1').empty()  # 清空标签内部所有的内容,标签还在

jQuery事件

  • 两种绑定事件的方式

# 第一种
$('#d1').click(function(){
    alert('第一种')
})

# 第二种(功能更强大,支持事件委托)
$('#d1').on('click',function(){
    alert('第二种')
})
  • 克隆事件

<button id="d1">影分身</button>
<script>
    $('#d1').on('click',function () {
        // console.log(this)  // this指代是当前被操作的标签对象
        // $(this).clone().insertAfter($('body'))  // clone默认情况下只克隆html和css 不克隆事件
        $(this).clone(true).insertAfter($('body'))  // 括号内加true即可克隆事件
    })
</script>

自定义模态框

 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <style>
        .cover{
            position: fixed;
            top:0;
            left: 0;
            right:0;
            bottom:0;
            background-color: darkgrey;
            z-index: 99;
        }
        .model {
            width:400px;
            height:200px;
            position: fixed;
            left: 50%;
            bottom:50%;
            margin-top: 100px;
            margin-left: 200px;
            background-color:wheat;
            z-index: 100;
        }
        .hide {
            display:none;
        }
    </style>
</head>
<body>
<div class="hide">我是最底层的</div>
<div class="cover hide">
</div>
<div class="model hide">
    <label for="l1">
         <input type="text" id="l1">username:
    </label><label for="l2">
     <input type="password" id="l2">password:
     <button class="c2">回去</button>
</label>
</div>
    <button class="c1">出来</button>
<script>
        $('.c1').on('click',function(){
            let coverEle = $('.cover')[0]  // 获得单个的标签对象
            let modelEle = $('.model')[0]
            $(coverEle).removeClass("hide")  // 再将单个的标签对象转成jq对象,操作属性
            $(modelEle).removeClass("hide")
        })
        $('.c2').on('click',function(){
            let coverEle = $('.cover')[0]
            let modelEle = $('.model')[0]
            $(coverEle).addClass("hide")
            $(modelEle).addClass("hide")
        })
</script>
</body>
  • 左侧菜单栏

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <style>
        .menu {
            background-color: #e2b9b9;
            width:400px;
            height:500px;
            position:fixed;
        }
        .title {
            font-size: 38px;
            color:black;
            background-color: greenyellow;
            border:3px darkred solid;
        }
        .items {
            font-size: 16px;
            color: #eecaca;
            background-color: #42310f;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div class="menu">
    <div class="title">早餐菜单:
        <div class="items hide">1包子</div>
        <div class="items hide">2馒头</div>
        <div class="items hide">3豆浆</div>
    </div>
    <div class="title">午餐菜单:
        <div class="items hide">1拉面</div>
        <div class="items hide">2黄焖鸡</div>
        <div class="items hide">3冒菜</div>
    </div>
    <div class="title">晚餐菜单:
        <div class="items hide">1火锅</div>
        <div class="items hide">2烤串</div>
        <div class="items hide"></div>
    </div>
</div>
<script>
    $('.title').on('click',function(){
        $('.items').addClass('hide')
        $(this).children().removeClass('hide')
    })
// 尝试用一行代码搞定上面的操作

效果图:

  • 返回顶部

<script>
    $(window).scroll(function () {
        if($(window).scrollTop() > 300){
            $('#d1').removeClass('hide')
        }else{
            $('#d1').addClass('hide')
        }
    })
</script>
  • 自定义登录校验

    在获取用户的用户名和密码的时候 用户如果没有填写 应该给用户展示提示信息

<p>username:
    <input type="text" id="username">
    <span style="color: red"></span>
</p>
<p>password:
    <input type="text" id="password">
    <span style="color: red"></span>
</p>
<button id="d1">提交</button>

<script>
    let $userName = $('#username')
    let $passWord = $('#password')
    $('#d1').click(function () {
        // 获取用户输入的用户名和密码 做校验
        let userName = $userName.val()
        let passWord = $passWord.val()
        if (!userName){
            $userName.next().text("用户名不能为空")
        }
        if (!passWord){
            $passWord.next().text('密码不能为空')
        }
    })
    $('input').focus(function () {
        $(this).next().text('')
    })
</script>
  • input实时监控

<input type="text" id="d1">

<script>
    $('#d1').on('input',function () {
        console.log(this.value)  
    })
</script>
  • hover事件

<script>
    // $("#d1").hover(function () {  // 鼠标悬浮 + 鼠标移开
    //     alert(123)
    // })

    $('#d1').hover(
        function () {
            alert('我来了')  // 悬浮
    },
        function () {
            alert('我溜了')  // 移开
        }
    )
</script>
  • 键盘按下事件
<script>
    $(window).keydown(function (event) {
        console.log(event.keyCode)
        if (event.keyCode === 16){
            alert('你按了shift键')
        }
    })
</script>

猜你喜欢

转载自www.cnblogs.com/zhangtieshan/p/12927085.html