• jQuery中的元素操作


    jQuery元素操作

    通过jQuery可以操作控制元素的样式,文本,属性等

    jquery样式操作

    css操作行内样式

    // 获取div的样式
    $("div").css("width");
    $("div").css("color");
    
    
    //设置div的样式
    $("div").css("width","30px");
    $("div").css("height","30px");
    $("div").css({fontSize:"30px",color:"red"});
    

    特别注意
    选择器获取的多个元素,获取信息获取的是第一个,比如:$(“div”).css(“width”),获取的是第一个div的width。

    类名class操作

    操作样式类名

    $("#div1").addClass(“divClass2”) //为id为div1的对象追加样式divClass2
    $("#div1").removeClass(“divClass”) //移除id为div1的对象的class名为divClass的样式
    $("#div1").removeClass(“divClass divClass2”) //移除多个样式
    $("#div1").toggleClass(“anotherClass”) //重复切换anotherClass样式

    文本操作

    1、html() 取出或设置html内容

    // 取出html内容
    
    var $htm = $('#div1').html();
    
    // 设置html内容
    $('#div1').html('<span>添加文字</span>');
    

    2、text() 取出或设置text内容

    // 取出文本内容
    
    var $htm = $('#div1').text();
    
    // 设置文本内容
    
    $('#div1').text('<span>添加文字</span>');
    

    属性操作

    1、attr() 取出或设置某个属性的值

    // 取出图片的地址
    
    var $src = $('#img1').attr('src');
    
    // 设置图片的地址和alt属性
    
    $('#img1').attr({ src: "test.jpg", alt: "Test Image" });
    
    //也可以用户设置class属性
    $('#abc').attr('class','all')
    
    //也可以自定义 属性
    $('#abc').attr('love','iloveyou')
    

    2、removeattr()删除属性

    $('#abc').removeattr('class')
    
    $('#abc').removeattr('love')
    
  • 相关阅读:
    JVisualVM简介与内存泄漏实战分析
    高并发性能提升和超卖的解决方案
    ehcache应用场景及集群同步(RMI)
    一台机器配置多个tomcat的实践经验
    事务范围数据库读写分离失败
    基于spring的数据库读写分离
    Zookeeper linux下使用
    Zookeeper集群
    Dubbo入门实例(二)
    Zookeeper安装与启动
  • 原文地址:https://www.cnblogs.com/victorfengming/p/11930973.html
Copyright © 2020-2023  润新知