【问题标题】:jquery don´t accept property, cause given string and not objectjquery不接受属性,导致给定字符串而不是对象
【发布时间】:2021-05-01 12:43:16
【问题描述】:

说明:

我尝试动态获取 HTML-Object 的值。所以我在 Object 上写了一个原型函数 select。它在控制台上工作,但不在脚本中。一个 jquery 属性有一些反对它的东西。

错误:

Uncaught TypeError: can't assign to property "guid" on "innerText": not an object

相关对象的输出:

Object { 0: th, 1: th, 2: th, 3: th, 4: th, 5: th, length: 6, prevObject: {…} }

对象上的功能选择:

Object.prototype.select = function(what)
{
    return this.map(function() {
        return this[what];
    }).get();
}

来电:

label.select('innerText')

这是一个已知的错误吗?有解决方法吗?调试器只是与 jquery 中的一个点有关:

S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++)

已经解决了:

function getData(data)
{
    return $(data).map(function() {
        return this.value;
    }).get();
}

【问题讨论】:

  • 嗨!请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets([<>] 工具栏按钮)的 runnable 问题; here's how to do one.
  • 你试过obj[what]吗?它返回保存在哪个变量中的属性的 obj 值,如果不存在则返回 undefined

标签: javascript jquery object html-object


【解决方案1】:

从不Object.prototype 对象添加属性是个好主意。用这样的简单赋值来添加它们是一个特别是的坏主意,这样它们就可以枚举了。此外,查看select 函数的内容,请注意几乎没有对象具有map 方法。 (数组是唯一带有map 的内置对象。jQuery 对象也有。)

我强烈建议不要向Object.prototype 添加任何内容。

但如果你还是这样做了,就让你添加的内容 *non-enumerable`:

Object.defineProperty(Object.prototype, "select", {
    value() {
        // ...your code here
    },
    writable: true,
    configurable: true,
});

仍然不是一个好主意,因为库拥有自己的专用对象并不少见,这些对象很可能有一个 select 方法(例如 jQuery 对象),设置你冲突。但至少如果你让它不可枚举,该属性将不会出现在for-in 循环和类似的循环中。

【讨论】:

    【解决方案2】:

    如果这是一个 jQuery 特定用例,您可以创建一个 jQuery 插件函数。

    类似:

    (($) => {
      // $.fn is alias for $.prototype
      $.fn.getArr = function(what) {
        return this.map((i,el) => $(el)[what]()).get();
      }
    })(jQuery)
    
    console.log($('p').getArr('text'))
    console.log($('input').getArr('val'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p>Para 1</p>
    <p>Para 2</p>
    <input value="one" />
    <input value="two" />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 2012-07-08
      • 2020-01-14
      相关资源
      最近更新 更多