博客列表 >JQuery初学习之`attr()`、`css()`、`val()`、`html()`、`text()`方法的学习

JQuery初学习之`attr()`、`css()`、`val()`、`html()`、`text()`方法的学习

景云
景云原创
2021年03月12日 12:48:47629浏览

1.attr()方法:获取/设置元素属性

需先引入JQuery

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
html

  1. <form action="index.php" method="POST">
  2. <input type="text" name="username" />
  3. <input type="password" name="password" />
  4. </form>

1.1 attr(name):getter 获取元素属性

例如获取表单属性

  1. const form=$("form");
  2. console.log(form.attr("action"));//index.php

1.2 attr(name,value):setter 设置元素属性

例如设置表单属性

  1. const form=$("form");
  2. form.attr("action","admin/index.php");
  3. console.log(form.attr("action"));//admin/index.php

第二个参数可以使用回调函数

  1. form.attr("action",()=>{
  2. let method=form.attr("method").toUpperCase();
  3. return method==="GET"?"index.php?username=Jy":"admin/index.php";
  4. });
  5. console.log(form.attr("action"));//如果为get则返回index.php?username=Jy;post则返回admin/index.php

2.css():获取/设置元素的行内样式

需先引入JQuery

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
css

  1. <style>
  2. form{
  3. width: 100px;
  4. }
  5. input{
  6. width: 95%;
  7. }
  8. </style>

html

  1. <form action="index.php" method="POST">
  2. 帐号: <input type="text" name="username" />
  3. 密码:<input type="password" name="password" />
  4. </form>

2.1 css(name):getter 获取元素行内样式

例如获取表单宽度

  1. const form=$("form");
  2. console.log(form.css("width"));//100px

使用原生style只能获取style上的行内样式

  1. console.log(document.querySelector("form").style.width);//无法获取

css样式表里的样式必须使用计算样式才可以获取

  1. console.log(window.getComputedStyle(document.querySelector("form"),null).getPropertyValue("width"));//100px

2.2 css(name,value):setter 设置元素行内样式

例如设置表单边框;多个参数用{}包裹,并用,隔开即可

  1. const form=$("form");
  2. form.css("border","2px solid red");//边框变为红色;

第二个参数可以使用回调函数

  1. form.css("color",()=>{
  2. const colors=["red","blue","yellow"];
  3. let i=Math.floor(Math.random() * colors.length);//Math.floor:向下取整;Math.random:0-1之间随机取值
  4. return colors[i];
  5. });
  6. //字体颜色将随机更换

3. val():设置/获取表单控件的value属性

需先引入JQuery

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
html

  1. <form action="index.php" method="get">
  2. 帐号:<input type="text" name="username" value="Jy" />
  3. 密码:<input type="password" name="password" value="123456" />
  4. 性别:
  5. <label for="man"></label>
  6. <input type="radio" name="sex" id="man" value="1" />
  7. <label for="woman"></label>
  8. <input type="radio" name="sex" id="woman" value="0" checked/>
  9. </form>
  1. <script>
  2. console.log($("input[name='username']").val());//Jy
  3. console.log($("input:password").val());//123456
  4. console.log($("input:radio:checked").val());//0
  5. $("input[name='username']").val("Jy2");//账号的值变为Jy2
  6. </script>

4. html()等同与innerHTML、text()等同于innerText/textContent

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议