jQuery 中DOM对象与js中DOM对象的转换

202 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="jquery-3.4.1.js"></script>
  <script>
    // 入口函数
    jQuery(document).ready(function () {

      // 1. js对象转换成jQuery对象。 $(js对象);
      // 2. jQuery转换成js对象。 1. jQuery对象[索引值];  2. jQuery对象.get(索引值) // 这里是直接标签的索引值,不是0获取标签数组在使用索引值获取标签,而是直接使用索引值获取到标签

      var box = document.getElementById('box');
      var classBoxs = document.getElementsByClassName('box');
      var divs = document.getElementsByTagName('div');

      // jQuery获取DOM返回得到永远是一个数组,数组中包含着合原生js中的DOM对象
      var jqBox = $('#box');
      var jqClassBoxs = $('.box');
      var jqDivs = $('div');

      console.log(box);
      console.log(jqBox);
      console.log('----------------------------');
      console.log(classBoxs);
      console.log(jqClassBoxs);
      console.log('----------------------------');
      console.log(divs);
      console.log(jqDivs);

      /*
      <div id="box"></div>
      jQuery.fn.init [div#box]
      ----------------------------
      HTMLCollection(2) [div.box, div.box]
      jQuery.fn.init(2) [div.box, div.box, prevObject: jQuery.fn.init(1)]
      ----------------------------
      HTMLCollection(4) [div, div.box, div#box, div.box, box: div#box]
      jQuery.fn.init(4) [div, div.box, div#box, div.box, prevObject: jQuery.fn.init(1)]
      */

      // 原生 DOM 转换成 jQuery DOM 对象
      box = $(box);
      classBoxs = $(classBoxs);
      divs = $(divs);

      console.log(box);
      console.log(jqBox);
      console.log('----------------------------');
      console.log(classBoxs);
      console.log(jqClassBoxs);
      console.log('----------------------------');
      console.log(divs);
      console.log(jqDivs);

       /*
      jQuery.fn.init [div#box]
      jQuery.fn.init [div#box]
      ----------------------------
      jQuery.fn.init(2) [div.box, div.box]
      jQuery.fn.init(2) [div.box, div.box, prevObject: jQuery.fn.init(1)]
      ----------------------------
      jQuery.fn.init(4) [div, div.box, div#box, div.box]
      jQuery.fn.init(4) [div, div.box, div#box, div.box, prevObject: jQuery.fn.init(1)]
      */

      // 设置 css()
      divs.css({
        'width': 100,
        'height': 100,
        'border': '1px solid red',
        'margin': 10
      });
      box.css('background', 'red');
      classBoxs.css('background', 'yellow');

      // jQuery DOM 对象转成原生 DOM 对象
      // jqBox = jqBox[0]
      // jqClassBoxs = jqClassBoxs[0]
      // jqDivs = jqDivs[0]
      jqBox[0].style.backgroundColor = 'green';
      jqDivs.get(1).style.backgroundColor = 'pink';
    })
  </script>
</head>
<body>
  <div></div>
  <div class="box"></div>
  <div id="box"></div>
  <div class="box"></div>
  <div"></div">
</body>
</html>
  • demo 效果: