使用 jquery returns 访问数据属性未定义?

Accessing data attribute using jquery returns undefined?

在我的视图中,我有一个按钮如下:

<button data-assigned-id="@IdUser" onclick="updateClick()" type="button" class="btn btn-sm btn-default"></button>

我的div

<div id="partial_load_div">

</div>

脚本

function updateClick() {
    var id = $(this).data('assigned-id');
    $('#partial_load_div').show();
    $('#partial_load_div').load('/Users/UpdatePartial?id=' + id);
}

id 总是显示为未定义,我检查了 @IdUser 总是值

然后在 chrome 开发中我得到了错误

GET http://localhost:19058/Users/UpdatePartial?id=undefined 400(错误请求)

知道如何解决这个问题吗?

当使用 data() 读取数据属性时,您需要删除 - 驼峰式大小写值 。所以你想要:

var id = $(this).data('assignedId');

docs on data() 显示:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

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.


我没注意到你是怎么绑定点击事件的。如果要使用 $(this),则必须使用 jquery 绑定事件。所以你需要:

<button data-assigned-id="works" id="button">
clickme</button>

$(window).ready(function() {
     //bind the event using jquery not the onclick attribute of the button
     $('#button').on('click', updateClick);

});


function updateClick() {
    alert($(this).data('assignedId'));
}

Working fiddle

在您当前的脚本中,$(this) 指的是没有 data- 属性的 Window 对象(不是您的按钮),因此它的 undefined.

您可以通过将元素传递给函数来解决这个问题

<button data-assigned-id="@IdUser" onclick="updateClick(this)" type="button" ... ></button>
function updateClick(element) {
    var id = $(element).data('assigned-id');
    ....

然而,更好的方法是使用 Unobtrusive Javascript 而不是用行为污染您的标记。

<button data-assigned-id="@IdUser" id="mybutton" type="button" class="btn btn-sm btn-default"></button>
$('#mybutton').click(function() {
    var id = $(this).data('assigned-id'); // $(this) refers to the button
    ....
});

就我的用法而言,即使该属性是 data-assignedId(Camel 大小写),在检索它时您也必须使用 data('assignedid')。使用驼峰式大小写返回未定义。