使用jQuery访问数据属性返回未定义? [英] Accessing data attribute using jquery returns undefined?

查看:69
本文介绍了使用jQuery访问数据属性返回未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Inside my view i have a button as follow:

<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始终具有值

The id is always shows as undefined, i checked and @IdUser has always value

然后在chrome dev中我得到了错误

then in chrome dev i got the error

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

GET http://localhost:19058/Users/UpdatePartial?id=undefined 400 (Bad Request)

有什么办法解决这个问题吗?

Any idea how to fix this?

推荐答案

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

In your current script, $(this) refers to the Window object (not your button) which does not have a data- attribute so its undefined.

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

You could solve this by passing the element to the function

<button data-assigned-id="@IdUser" onclick="updateClick(this)" type="button" ... ></button>

function updateClick(element) {
    var id = $(element).data('assigned-id');
    ....

但是,更好的方法是使用不干扰Java语言,而不要用行为来污染标记. /p>

However a better approach is to use Unobtrusive Javascript rather than polluting your markup with behavior.

<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
    ....
});

这篇关于使用jQuery访问数据属性返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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