Javascript:链接 jQuery 等元素

标签 javascript method-chaining

我试图在一定程度上复制 jQuery 的元素操作。现在我发现非常有用的是 .first()选择器。我希望能够像这样链接函数;
getElement(selector).first().hasClass(className);

现在,我已经走了多远有两个问题(请注意,我的代码示例已最小化,所以请不要对错误处理发表评论。)

var getElement = function(selector, parent) {
  ret           = document.querySelectorAll(selector);
  this.element  = ret;
  this.hasClass = function(className) {
    className.replace('.', '');
    if(this.multiple())
    {
      console.log('Cannot use hasClass function on multiple elements');
      return false;
    }
  };

  this.first = function() {
    this.element = this.element[0];
    return this;
  };
  return this;
};

我当前的问题

如果我调用我的函数;

var $test = getElement('.something'); //result: nodelist with .something divs

如果我调用结果中的第一个元素;

$test.first(); //Result: First div, perfect!

但是,现在如果我打电话 $test再次,它将取代 elements属性的结果为 first() ,这意味着我已经“失去”了我的旧值(value)观。我不想失去它们,我只想要first()用于该特定功能的函数。那我要$test再次返回所有元素。 另外,回顾first()现在最终将是 undefined ,因为 this 中只剩下 1 个元素因为它已从对象内删除了旧元素。

再次尝试

现在,我还尝试通过返回第一个子对象而不是整个类对象来稍微扭转它;

this.first = function() {
  return this.element[0];
};

但是,我会 $test.first().hasClass(className); //Returns ERROR, method hasClass undefined

这是因为.hasClass存在于原版 this ,由于我现在返回该元素,因此不再返回该元素。

我试图从 jQuery 库中获取一些东西,尽管这让我更加困惑......

我已经用谷歌搜索了这个主题,但是通过我找到的所有“链接方法”解决方案,它们似乎都覆盖了对象的原始值,这不是我想要发生的情况。另一种解决方案实际上要求我一遍又一遍地重新启动该对象,这对我来说似乎不是很有效......任何帮助都会受到赞赏。我假设我的处理方式完全错误。

-- 如果您可以帮助我,请解释一下您的解决方案为何有效。我真的觉得如果我理解了这一点,我对 javascript 的理解可以进一步扩展很多。我只需要解决这个结构性(?)问题。

最佳答案

first() 这样的方法不应该修改 this,它应该创建一个新对象并返回它。您只能在修改元素的方法中使用 return this;,而不是返回从该元素派生的信息。

this.first = function() {
    return new getElement(this.element[0]);
};

请注意,您必须使用 new getElement 来创建对象,而不仅仅是 getElement

这还需要更改构造函数,以便它可以接受选择器字符串或元素:

var getElement = function(selector, parent) {
    var ret = typeof selector == "string" ? document.querySelectorAll(selector) : [selector];
    ...
}

您还应该考虑以正确的 OO 方式执行此操作,将方法放入原型(prototype)中,而不是在每个对象中定义它们。

var getElement = function(selector, parent) {
  var ret = typeof selector == "string" ? document.querySelectorAll(selector) : [selector];
  this.element = ret;
};

getElement.prototype.hasClass = function(className) {
  className.replace('.', '');
  if (this.multiple()) {
    console.log('Cannot use hasClass function on multiple elements');
    return false;
  }
};

getElement.prototype.first = function() {
  return new getElement(this.element[0])
};

关于Javascript:链接 jQuery 等元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432698/

相关文章:

javascript - Sencha touch 中的数字签名选项

python - 在python中返回 self

javascript - 将所有类都封装在 try/catch javascript 中?

javascript - Meteor.publish 回调未被调用

javascript - 返回值未定义

javascript - 如何适配Wordpress WP Tiles Plugin/Pixellab的tiles.js

javascript - 如何在播放后隐藏leafletJS中的视频叠加层?

ruby - ActiveRecord 如何检测链中的最后一个方法调用?

error-handling - 在管理错误的同时在管道中链接 REST 调用

javascript - 如何通过链接早期的附加方法将事件附加到表单的 onSubmit 事件?