zoukankan      html  css  js  c++  java
  • 由$(this).attr('id')引出的一点感想

    这几个月一直在学习JS,对HTML不够重视,有些很基础的东西还没完全掌握,于是暴露了问题。

    在看DOM元素属性时突然看到了id属性,不由得想起之前我竟然是这么来获取id的

    $('#btn').on('click', function() {
      var id = $(this).attr('id');
      //... 
    });

    this指向被点击的dom元素,id的话这样取就好了

    $('#btn').on('click', function() {
      var id = this.id;
      //... 
    });

    应该多使用DOM元素本身,因为每一次$()都会创建一个新的jQuery对象

    然而有时我们想要用jQuery的各种方法时,可以这样

    (function() {
        $.extend(jQuery, {
            temp: (function() {
                var temp = $({});
                return function(element) {
                    temp[0] = element;
                    return temp;
                }
            })()
        });
    })();
    
    $('#btn').on('click', function() {
      var html = $.temp(this).next().html();
      //...
    });

    每次传入一个DOM元素都只是替换了temp这个jQuery对象里的DOM元素,而避免创建新的jQuery对象

  • 相关阅读:
    rzc generate exited with code -2147450730.
    c#WebService动态调用
    c#BarTender打印,打印微调
    记一次ios下h5页面图片显示问题
    FID
    RSA密钥对生成,并解析公钥指数和模数
    angularjs-6
    angularjs-5
    angularjs-4
    angularjs-4
  • 原文地址:https://www.cnblogs.com/coiorz/p/4822058.html
Copyright © 2011-2022 走看看