gpt4 book ai didi

jquery - 使用 jquery 访问数据属性返回未定义?

转载 作者:行者123 更新时间:2023-12-03 22:09:00 25 4
gpt4 key购买 nike

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

<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 dev 中我收到错误

获取 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.

<小时/>

我没有注意到你是如何绑定(bind)点击事件的。如果您想使用 $(this) 您必须使用 jquery 绑定(bind)事件。所以你需要:

<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

关于jquery - 使用 jquery 访问数据属性返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36451233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com