官术网_书友最值得收藏!

Plain JavaScript versus jQuery

Even a task as simple as this can be complicated without jQuery at our disposal. In plain JavaScript, we could add the highlight class in this way:

window.onload = function() {
  var divs = document.getElementsByTagName('div');
  for (var i = 0; i < divs.length; i++) {
    if (hasClass(divs[i], 'poem-stanza')
      && !hasClass(divs[i], 'highlight')) {
      divs[i].className += ' highlight';
    }
  }

  function hasClass( elem, cls ) {
    var reClass = new RegExp(' ' + cls + ' ');
    return reClass.test(' ' + elem.className + ' ');
  }
};

Listing 1.3

Despite its length, this solution does not handle many of the situations that jQuery takes care of for us in Listing 1.2, such as:

  • Properly respecting other window.onload event handlers
  • Acting as soon as the DOM is ready
  • Optimizing element retrieval and other tasks with modern DOM methods

We can see that our jQuery-driven code is easier to write, simpler to read, and faster to execute than its plain JavaScript equivalent.

主站蜘蛛池模板: 乐陵市| 沙湾县| 甘德县| 乌什县| 安化县| 苏尼特左旗| 邵东县| 郎溪县| 会东县| 繁峙县| 永顺县| 和平区| 安西县| 云梦县| 上思县| 新源县| 兰溪市| 司法| 伊金霍洛旗| 巴南区| 弥勒县| 南涧| 抚远县| 文成县| 龙海市| 肥城市| 江陵县| 鄂温| 黑山县| 碌曲县| 桃江县| 宁乡县| 保定市| 临桂县| 吉林省| 鄂州市| 张家川| 固原市| 旌德县| 岑溪市| 尉犁县|