Home > Web Front-end > JS Tutorial > About the usage of Attr in JS

About the usage of Attr in JS

小云云
Release: 2018-01-26 13:25:57
Original
3201 people have browsed it

This article mainly introduces the usage of attr in js through example code. It is very good and has reference value. Friends who need it can refer to it. I hope it can help everyone.

The specific code is as follows:


<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $("#btn").click(function(){
      //使用attr(name)获取属性值:
      alert($("p").attr("title"));//你最喜欢的水果是。
      alert($("ul li:eq(1)").attr("title"));//橘子汁
      alert($("ul li:eq(1)").attr("alt"));//123
      //使用attr(name, value)改变属性值:
      //$("ul li:eq(1)").attr("title", "还是吗?");//将第二个li的title的值改变
      //使用attr(name, fn)设置属性的函数值
      $("ul li:eq(1)").attr("title", function(){
          return "我就不信";
      });//将第二个li的title的值改变
      alert($("ul li:eq(1)").attr("title"));//我就不信
      //使用attr(name, properties)将一个“名/值”形式的对象设置为所有匹配元素的属性
      $("ul li:eq(1)").attr({title: "第一个", alt: "第二个"});
      alert($("ul li:eq(1)").attr("title"));//第一个
      alert($("ul li:eq(1)").attr("alt"));//第二个
    });
  });
</script>
<p title="你最喜欢的水果是。">你最喜欢的水果是?</p>
<ul>
  <li title="苹果汁">苹果</li>
  <li title="橘子汁" name="好吃" alt="123">橘子</li>
  <li title="菠萝汁">菠萝</li>
</ul>
<input type="button" value="点击" id="btn"/>
Copy after login

Related recommendations:

Using attr in jQuery Detailed explanation of the similarities and differences of (), prop(), val() to obtain value

The difference between .attr() and .data() in jQuery

When to use attr() and when to use prop() in jquery?

The above is the detailed content of About the usage of Attr in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template