我将如何在纯JavaScript中实现类似jquerys .data()的东西? [英] how would i implement something like jquerys .data() in pure javascript?

查看:99
本文介绍了我将如何在纯JavaScript中实现类似jquerys .data()的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为项目工作的项目需要jQuery .data()实现的纯JavaScript版本.

A project I am working on for works wants a pure JavaScript version of the .data() implementation of jQuery.

我想重复一遍.

我进行了搜索,并将jQuery.data()存储在哪里?它在jQuery中的存储位置.

I did a search and Where is jQuery.data() stored? shows where in jQuery it is stored.

我希望我可以将数据段附加到HTML元素上以便以后访问.

I was hoping that i could just attach a datasegment to an HTML element for accessing later.

由于jQuery是Javascript,因此可以在其中查看,但是它利用了jQuery对象,这就是我要抽象的内容.我发现有一种方法可以将像数据集这样的哈希表与JavaScript关联起来并将其附加到对象上.

Since jQuery is Javascript, I can look there, but it makes use of the jQuery objects, which is what I am trying to abstract. I figured there was some sort of way to associate a hash table like dataset with JavaScript and attach it to an object.

推荐答案

http://jsfiddle.net/npXQx/

显示可以在对象中创建.data,然后将其保存.您可以访问两次,并且数据在那里.

shows you can create a .data in the object and then it is preserved. You can access it twice, and the data is there.

此示例显示了一个简单的字符串分配和一个函数,并且多次调用了该函数.

This example shows a simple string assignment and a function and it being called multiple times.

var item = document.getElementById("hi");
console.log(item);

item.data = {getType: function(){return this.TYPE},TYPE:"winner"};

var out = item.data.getType();
console.log("out", out);

var two = document.getElementById("hi")
console.log("should say 'winner': ", two.data.getType());

这篇关于我将如何在纯JavaScript中实现类似jquerys .data()的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆