jquery 数据()不工作

jquery data() not working

我在使用 jquery 数据函数时遇到了一些问题。

$(e.target).data("unitId") 未定义。

一段时间以来我一直在尝试解决此问题,但找不到我的代码有什么问题。

有人看到这里出了什么问题吗?

var SomeView = Backbone.View.extend({
    el: '#sidebar',
    events: {
        "click .link-unit": "route"
    },
    initialize: function(){

        this.render();

    },
    render: function(){
        this.$el.html('<div class="link-unit" data-unitId="some data">some text</div>');
    },
    route: function(e){
        console.log($(e.target).data('unitId'));
    },
});

改为尝试:

$(e.target).data("unitid")

始终尝试在您的标记和代码中使用所有小写字母,这样您就不会 运行 陷入此类问题。

For example, given the following HTML:

 <div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

All of the following jQuery code will work.

$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

The second statement of the code above correctly refers to the data-last-value attribute of the element. In case no data is stored with the passed key, jQuery searches among the attributes of the element, converting a camel-cased string into a dashed string and then prepending data- to the result. So, the string lastValue is converted to data-last-value.

参考:https://api.jquery.com/data/

当您使用驼峰式请求 .data("dataId") 时,jQuery 会将其转换为对属性 "data-data-id" 的请求。

您可以通过不使用驼峰命名法来修复它。例如,如果您在 HTML 和 jQuery 中都使用全小写的属性名称,则一切正常。或者,您可以将 HTML 更改为使用 "data-data-id" 作为属性名称,并在 HTML.

中保留驼峰式

此解释来自the jQuery doc:

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

$( "div" ).data( "lastValue" ) === 43;

The ... above code correctly refers to the data-last-value attribute of the element. In case no data is stored with the passed key, jQuery searches among the attributes of the element, converting a camel-cased string into a dashed string and then prepending data- to the result. So, the string lastValue is converted to data-last-value.

工作演示:http://jsfiddle.net/jfriend00/uaoL0hdn/