【问题标题】:JavaScript custom library css function not workingJavaScript自定义库css函数不起作用
【发布时间】:2018-11-07 18:26:59
【问题描述】:

我最近为 JavaScript 制作了一个自定义框架,但我的 '.css()' 函数不能用作对象表示法,这是我的代码的一部分:

const aps = function(selector) {
  if (!(this instanceof aps)) {
    return new aps(selector);
  };
  this.el = document.querySelectorAll(selector);

  var about = {
    Version: "0.3",
    Author: "AppleProSchool, Adam Izgin",
    Created: "Fall 2018, Tuesday 5, November",
    Updated: "Tuesday 6, November",
  }
};
aps.prototype.css = function(property, value) {
  this.el.forEach(function(element) {
    element.style[property] = value;
  });
  return this;
};

例如,如果我会这样做:

(window.onload = function() {
    aps('.test').css({ background: '#0f0' });//That does not return anything. Why?
});

但是当我这样做时:

(window.onload = function() {
    aps('.test').css('background', '#0f0');//It works.
});

我确实有一个红色背景的 div。

任何想法为什么?还是谢谢你。

【问题讨论】:

    标签: javascript frameworks


    【解决方案1】:

    您的函数需要两个参数:

    aps.prototype.css = function(property, value) {
    

    所以当你发送一个参数(一个对象)时:

    aps('.test').css({ background: '#0f0' })
    

    property 参数包含 {background:'#0f0'},无法正确提取:

    element.style[property]
    

    并且函数找不到value 所需的信息,因此将是undefined

    但是,当您发送两个参数时:

    aps('.test').css('background', '#0f0')
    

    它有效。


    如果您想使用 Object 语法,您需要更新您的函数以仅期望一个参数,并且该函数必须从该对象中“解包”它需要的数据。它看起来像这样:

    aps.prototype.css = function(obj) {
      this.el.forEach(function(element) {
        // Use the first key name in the object and the first key value
        element.style[Object.keys(obj)[0]] = Object.values(obj)[0];
      });
      return this;
    };
    

    【讨论】:

    • 是的,好的。但是我怎样才能让它像一个对象呢?我发现这样更有效率。
    • @codeWithMe 需要明确的是,您并没有要求一种使其与对象变体一起使用的方法。您问有什么想法吗?。但是,我已经更新了我的答案以说明如何做到这一点。
    • 非常感谢您非常的回答,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2020-02-03
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多