0

jqueryオブジェクトにプロパティを追加したい。jquery のコンテキストにプロパティを追加しようとしています。jquery オブジェクト console.log($(this)) をコンソール化します。これはオブジェクトのように見えます。しかし、コードを修正しようとすると、フィドルが機能しません

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

ここに画像の説明を入力

4

3 に答える 3

2

HTML の data- 属性にデータを追加できるため、次のオプションを保存できます。

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

更新された jsfiddle はこちら: http://jsfiddle.net/8juvcxqg/

于 2015-04-28T09:08:19.157 に答える
1

問題は、新しい jQuery ラッパーが作成されるたびに $(this) を呼び出すと、以前のオブジェクトに追加したものが新しいオブジェクトで利用できなくなることです。

$(this) == $(this)which will returnを使用してテストできますfalse

正しい方法は、データ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()
})

デモ:フィドル

于 2015-04-28T09:10:55.957 に答える
0

これには jquery も必要ありません。

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

ワーキングデモ

于 2015-04-28T09:08:58.137 に答える