简体   繁体   English

从数据属性获取数据

[英]getting data from data attribute

I set a data attribute for a user on a link like this 我在这样的链接上为用户设置了数据属性

  <input type="button" class="btn" data-user={"user": "<%= @user.name %>"}  value="Start" id="game">

In the javascript function that listens for the click event, I did a console.log(e.target) and it printed the whole thing to the console. 在侦听click事件的javascript函数中,我做了一个console.log(e.target) ,它将整个内容打印到控制台。

<input type="button" class="btn" data-user={"user": "<%= @user.name %>"}  value="Start" id="game">

If I do console.log(e) ie with no e.target, it logs the jquery event, but the data attribute is undefined 如果我执行console.log(e)即没有e.target,则会记录jquery事件,但数据属性未定义

data: undefined

I'm trying to pull the username from the data attribute but don't know how to get it from this 我正在尝试从数据属性中提取用户名,但不知道如何从中获取它

<input type="button" class="btn" data-user={"user": "<%= @user.name %>"}  value="Start" id="game">

and I don't know why data is undefined when I log just the event. 当我只记录事件时,我不知道为什么数据未定义。

I'd be very grateful if you can assist me with this. 如果你能帮助我,我将非常感激。 Thanks in advance. 提前致谢。

Your HTML is ... unique? 你的HTML是......独一无二的吗? Instead of this: 而不是这个:

data-user={"user": "<%= @user.name %>"}

Try this: 尝试这个:

data-user="<%= @user.name %>"

Then you can get the data with the standard jQuery .data() technique (since you mentioned jQuery): 然后你可以使用标准的jQuery .data()技术获取数据(因为你提到了jQuery):

var user = $('#game').data('user');

您可以按如下方式访问DOM对象中的数据:

var data = $(e.target).attr("data-user");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM