我爱编程

七、JQuery-5、通过JQuery获取或者设置网页元素

2018-06-06  本文已影响0人  cybeyond

1、获取内容

text()、html()、val()

举例:'<input type="text" value="测试" id="name">'
$("#name").val() //得到结果:测试
'<div id="info"> <b>早上好</b></div>'
$("#info").text() //得到结果:显示文字 早上好 相当于DOM中的innerText
$("#info").html()//得到结果:显示标记 <b>早上好</b> 相关与DOM中的innerHTML

2、获取和设置属性

$("#info").attr("href","http://www.baidu.com");//将其链接改为www.baidu.com
用text(),html(),val()来设置元素值的时候,可以传入一个函数
对这个函数时有要求的:
(1)要有返回值,返回值就是用来设置元素的值
(2)有两个参数,i,s,其中i表示索引,s表示旧值

<html>
<head>
<meta http-equiv="Content-Type content="text/html;charset=gbk" />

<script type="text/javascript" src="jslib/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $(".info").html(function(index,old){  //html()中引入函数
            var str=old;
            if(index>0)
            {
                str="<b>" +old+ "</b>";//将第2、3个变成粗体
            }
            return str;
        });
    });
});

</script>
</head>
<body>
<div class="info">第一段测试文字</div>
<div class="info">第二段测试文字</div>
<div class="info">第三段测试文字</div>
<button>test</button>
</body>
</html>
执行结果
上一篇下一篇

猜你喜欢

热点阅读