【问题标题】:Add custom object in jquery's object在 jquery 的对象中添加自定义对象
【发布时间】:2015-04-28 09:06:22
【问题描述】:

我想在 jquery 对象中添加属性。我正在尝试在 jquery 的上下文中添加属性。我控制 jquery 对象 console.log($(this)),它看起来像一个对象。但是当我试图修改代码时不起作用fiddle

$('ul').click(function(){
    $(this).myul={'date':'28 april'}
    console.log($(this))
})

【问题讨论】:

  • 你为什么要这样做
  • 当你每次调用$(this) 时都会创建一个新的 jQuery 包装器

标签: jquery custom-object


【解决方案1】:

您可以在 HTML 中的 data- 属性中添加数据,因此可以选择存储:

$(this).data('myul', {'date':'28 april'});

更新的 jsfiddle 在这里:http://jsfiddle.net/8juvcxqg/

【讨论】:

    【解决方案2】:

    问题是当您每次创建新的 jQuery 包装器时调用 $(this) 时,您添加到前一个对象的每个内容在新对象中都将不可用。

    您可以使用$(this) == $(this) 对其进行测试,这将返回false。

    正确的方法是使用data api

    $('ul').click(function () {
        console.log('test', $(this) == $(this));//will be false since both the times different objects are returned
    
        console.group('Using cached object')
        var $this = $(this);//here we use a cached instance of the jQuery wrapper, this will work as long as you have a reference to $this - but is the wrong way
        $this.myul = {
            'date': '28 april'
        }
        console.log($this.myul);
        console.groupEnd()
    
        console.group('Using data api')
        $(this).data('myul', {
            'date': '28 april'
        });
        console.log($(this).data('myul'))
        console.groupEnd()
    })
    

    演示:Fiddle

    【讨论】:

      【解决方案3】:

      你甚至不需要 jquery:

       this['myul'] = '"date":"28 april"';
       console.log($(this))
      

      Working Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 2013-08-17
        相关资源
        最近更新 更多