无法使用 jQuery Data() API 设置数据属性 [英] Unable to set data attribute using jQuery Data() API

查看:23
本文介绍了无法使用 jQuery Data() API 设置数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MVC 视图中有以下字段:

@Html.TextBoxFor(model => model.Course.Title, new { data_helptext = "Old Text" })

在单独的 js 文件中,我想将 data-helptext 属性设置为字符串值.这是我的代码:

alert($(targetField).data("helptext"));$(targetField).data("helptext", "Testing 123");

alert() 调用工作正常,它在警报对话框中显示文本旧文本".但是,将 data-helptext 属性设置为Testing 123"的调用不起作用.旧文本"仍然是属性的当前值.

我是否错误地使用了对 data() 的调用?我在网上查过这个,我看不出我做错了什么.

这是 HTML 标记:

解决方案

中有提到.data() 文档

<块引用>

数据属性在第一次访问数据属性时被拉取,然后不再访问或改变(所有数据值然后存储在jQuery内部)

这也在 为什么不改变jQuery $.fn.data() 更新对应的html 5 data-* 属性?

下面关于我的原始答案的演示似乎不再起作用了.

更新答案

同样,来自 .data() 文档

<块引用>

在 jQuery 1.6 中更改了对带有嵌入破折号的属性的处理,以符合 W3C HTML5 规范.

所以对于 <div data-role="page"></div> 以下是正确的 $('div').data('role') === '页面'

我相当确定 $('div').data('data-role') 在过去有效,但现在似乎不再如此.我创建了一个更好的展示,它记录到 HTML 而不必打开控制台,并添加了一个额外的多连字符示例到camelCase data-attributes 转换.

更新演示 (2015-07-25)

另见 jQuery 数据 vs 属性?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div><a href="#" id="changeData"></a><table id="日志"><tr><th>Setter</th><th>Getter</th><th>调用getter的结果</th><th>注意</th></tr>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');var $log = $('#log');无功记录器;(记录器 = 函数(setter, getter, note) {注意 = 注意 ||'';eval('$changeMe' + setter);var 结果 = eval('$changeMe' + getter);$log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + 结果 + '</td><td>' + 注释 + '</td></tr>');})('', ".data('key')", "初始值");$('#changeData').click(function() {//将数据键设置为新值logger(".data('key', 'leia')", ".data('key')", "在 jQuery 节点对象上期望 leia 但 DOM 保持为 luke");//尝试通过 .attr 设置数据键并通过一些方法获取logger(".attr('data-key', 'yoda')", ".data('key')", "期望 leia (仍然) 在 jQuery 对象上,但现在 DOM 是 yoda");logger("", ".attr('key')", "expect undefined (no attr key)");logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");//奖励积分logger('', ".data('data-key')", "expect undefined (不能通过这个方法得到)");logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ 获取多连字符 <code>data-another-key</code>");logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (也支持在 jQuery 1.6+)");返回假;});$('#changeData').click();

<小时>

较旧的演示

<小时>

原答案

对于这个 HTML:

<a href="#" id="changeData">更改数据值</a>

和这个 JavaScript(使用 jQuery 1.6.2)

console.log($('#foo').data('helptext'));$('#changeData').click(function() {$('#foo').data('helptext', 'Testing 123');//$('#foo').attr('data-helptext', 'Testing 123');console.log($('#foo').data('data-helptext'));返回假;});

查看演示

使用 Chrome DevTools 控制台检查DOM,$('#foo').data('helptext', 'Testing 123'); 更新中看到的值控制台 但是 $('#foo').attr('data-helptext', 'Testing 123'); 可以.

I've got the following field on an MVC view:

@Html.TextBoxFor(model => model.Course.Title, new { data_helptext = "Old Text" })</span>

In a seperate js file, I want to set the data-helptext attribute to a string value. Here's my code:

alert($(targetField).data("helptext"));

$(targetField).data("helptext", "Testing 123");

The alert() call works fine, it shows the text "Old Text" in an alert dialog. However, the call to set the data-helptext attribute to "Testing 123" does not work. "Old Text" is still the attribute's current value.

Am I using the call to data() incorrectly? I've looked this up on the web, and I can't see what I'm doing wrong.

Here's the HTML markup:

<input data-helptext="Old Text" id="Course_Title" name="Course.Title" type="text" value="" />

解决方案

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();


Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

这篇关于无法使用 jQuery Data() API 设置数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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