简体   繁体   English

如何将此 jQuery 代码重写为 Javascript?

[英]How can I rewrite this jQuery code into Javascript?

I'm using a WordPress theme that only has about 10 lines of jQuery, yet it's using the 90kb jQuery file.我使用的 WordPress 主题只有大约 10 行 jQuery,但它使用的是 90kb jQuery 文件。 I want to change this jQuery code to Javascript, but I'm not very good at Javascript:我想把这个jQuery代码改成Javascript,但是我不太擅长Javascript:

jQuery('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a').live("click", function () {
  $href = jQuery(this).attr('href');
  $contentArea.fadeTo('fast', 0.2).load($href + ' #main-area', function () {
    $contentArea.fadeTo('fast', 1);
  });
  return false;
});


var $tabbed_area = jQuery('div#tabbed');
if ($tabbed_area.length) {
  $tabbed_area.tabs({
    fx: {
      opacity: 'toggle'
    }
  });
};

Thanks in advance!提前致谢!

Personally I'd persist with jQuery.我个人会坚持使用 jQuery。 Although there is "only about 10 lines jQuery" what it is doing is quite substantial.尽管“只有大约 10 行 jQuery”,但它所做的却是相当可观的。 By the time you have recreated a lot of what jQuery is providing you here you will have a fairly decent slab of javaScript to debug and maintain.当您重新创建 jQuery 在这里为您提供的许多内容时,您将拥有相当不错的 javaScript 板进行调试和维护。 That is the beauty of jQuery, to quote their tag line "write less, do more" Remember with jQuery you are eliminating a lot of annoying cross browser quirks.这就是 jQuery 的美妙之处,引用他们的标语“少写,多做”请记住,使用 jQuery,您将消除许多恼人的跨浏览器怪癖。

Edit: See tbranyen's answer for a practical example of why jQuery is worth it编辑:请参阅tbranyen 的回答,了解为什么 jQuery 值得的实际示例

Use a CDN version of jQuery, like Google's and you will be using jQuery that your uses may already have cached and therefore does not have to be downloaded again.使用 jQuery 的 CDN 版本,如Google 的,您将使用 jQuery,您的使用可能已经缓存,因此不必再次下载。 jQuery UI can also be served in the same way. jQuery UI 也可以以相同的方式提供服务。 See this article: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/见这篇文章: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/

EDIT编辑

Reading your question further "I'm not very good at javaScript" is all the more reason to stick with jQuery.进一步阅读您的问题“我不太擅长 javaScript”是坚持使用 jQuery 的更多理由。 Let it do all the heaving lifting for you.让它为你做所有的举重。 HOWEVER don't use jQuery as an excuse not to learn more about javaScript, the more you learn about javaScript the more you will be able to get out of jQuery. HOWEVER don't use jQuery as an excuse not to learn more about javaScript, the more you learn about javaScript the more you will be able to get out of jQuery.

My solution is fragmented, its not complete, and I do not expect points for this answer.我的解决方案是零散的,它不完整,我不希望这个答案得到分数。 This was me taking a stab at replicating jQuery's code in vanilla JS, purely as scientific justice to your question.这是我尝试在 vanilla JS 中复制 jQuery 的代码,纯粹是为了对您的问题进行科学公正。 I consider myself good at JavaScript, but even I know my limitations and time constraints.我认为自己擅长 JavaScript,但即使我知道自己的局限性和时间限制。 I only have one life on this planet and its honestly not worth my time to write out a tabs plugin and animation for your Wordpress site.我在这个星球上只有一个生命,老实说,我不值得花时间为您的 Wordpress 站点写一个标签插件和 animation。

Just take a look at the code difference.只需看一下代码差异。 If you're really scared about people downloading, you should ask yourself what makes your site so much different than the thousands/millions?如果你真的害怕人们下载,你应该问问自己是什么让你的网站与成千上万的网站有如此大的不同? of other sites that are visited by millions of people?数百万人访问的其他网站?

Writing this stuff is tedious, that's why if I have to do these things, I use jQuery.写这些东西很乏味,这就是为什么如果我必须做这些事情,我会使用 jQuery。 However , lets say you don't care about older browser support.但是,假设您不关心较旧的浏览器支持。 You didn't mention that, I have a solution at the very bottom that does more, but WILL not work with older browsers or work period for that matter.你没有提到这一点,我在最底层有一个解决方案,它可以做更多的事情,但不会与旧浏览器或工作期一起使用。

The original原本的

Very little code to do immensely complicated stuff.很少的代码可以做非常复杂的事情。

jQuery('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a').live("click", function () {
  $href = jQuery(this).attr('href');
  $contentArea.fadeTo('fast', 0.2).load($href + ' #main-area', function () {
    $contentArea.fadeTo('fast', 1);
  });
  return false;
});

Attempting to write from scratch尝试从头开始写

// Not even close to finished solution
(function(window, document) {
  var tabbed = document.getElementById('tabbed');

  // Semi-normalized event handling, not even a fraction as good as jQuery's
  function attachEvent(node, type, callback) {
    if(node.attachEvent) {
      return node.attachEvent('on'+type, function() {
        callback.apply(window.event.target, arguments);
      });
    }

    return node.addEventListener(type, function(e) {
      callback.apply(e.target, arguments);
    }, true);
  }

  // Semi-delegation again, not even a fraction of what jQuery offers
  attachEvent(document, 'click', function(e) {
    var href = this.href;
    var body = document.body;
    var elements = [];
    var slice = [].slice;
    var concat = elements.concat;

    // This is just the start of what it would take to emulate what jQuery is doing to match all those items
    // Without a reliable selector engine like querySelectorAll (not even that reliable) you'd need to match.
    elements = concat(slice.call(body.getElementById('main-tabbed-area').getElementsByTagName('a')));
    elements = concat(slice.call(body.getElementsByTagName('...');

    // Not even going to attempt fading
    // jQuery again does all this
  });

  if(tabbed && tabbed.tagName === 'div') {
    // No idea what tabs is? A plugin? Good luck!
  }

})(this, this.document);

Code is slightly more modern... but still jeesh look at all that code代码稍微更现代一些......但仍然看到所有这些代码

function xhr(url, callback) {
  var request = new window.XMLHttpRequest();
  request.open('GET', url, true);
  request.onreadystatechange = function(e) {
    if(e.readyState === 4) {
      callback(e.responseXML);
    }
  };
  request.send(null);
}

// No idea what contentArea is
var contentArea = ...???;

(function(window, document) {
  var tabbed = document.getElementsById('tabbed');

  document.addEventListener('click', function(e) {
    var href;
    var elements = document.querySelectorAll('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a');
    var match = false;

    elements.forEach(function(element) {
      if(this === element) {
        match = true;
      }
    });

    if(match) {
      href = e.target.href;

      // Some CSS3 class that does a fade out
      contentArea.classList.add('fadeOut');

      xhr(href, function(data) {
        var data = data.getElementById('main-area').innerHTML;
        contentArea.innerHTML = data;

        contentArea.classList.remove('fadeOut');

        // Some CSS3 class that does a fade in
        contentArea.classList.add('fadeIn');
      });

      return false;
    }
  }, true);

  if(tabbed && tabbed.tagName === 'div') {
    // Still no idea what tabs is? A plugin? Good luck!
  }
})(this, this.document);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM