简体   繁体   English

无法使用jQuery数据设置元素属性()

[英]Unable to Set Element Attribute Using jQuery data()

I'm having trouble updating elements from JavaScript. 我在从JavaScript更新元素时​​遇到问题。 My project is fairly complex but here's a tiny piece of it: 我的项目相当复杂,但这里只有一小部分:

myWebService(/*...*/)
.done(function (result) {
    var newRows = $(rows).clone();
    $('#drop-placeholder').after(newRows);
    $(newRows).data('test', 'ZZZZZZZZZZZZZZZZZZZZZZZ');
}

Using Chrome, I can watch these statements execute. 使用Chrome,我可以看到这些语句执行。 However, with newRows in the watch window, I can see that the attribute never gets added/updated. 但是,在监视窗口中使用newRows ,我可以看到该属性永远不会被添加/更新。 And, sure enough, after the call is done, I don't see the specified attribute on my page. 而且,确实,在完成调用后,我在页面上看不到指定的属性。

Can anyone see what I might be missing. 任何人都可以看到我可能会失踪的东西。 rows (and therefore newRows ) represents any number of table row elements. rows (因此newRows )表示任意数量的表行元素。

.data() sets background data that is handled purely by jQuery - it does not set HTML attributes. .data()设置纯粹由jQuery处理的背景数据 - 它不设置HTML属性。

If you are trying to set an attribute such as data-test in <div data-test="stuff"></div> you need to use .attr("data-test", variable) . 如果您尝试在<div data-test="stuff"></div>设置诸如data-test类的属性,则需要使用.attr("data-test", variable)

The setting the data via jQuery .data() does not set the attribute, only the underlying data store. 通过jQuery .data()设置data 不会设置属性,只会设置基础数据存储。 If you want to change the attribute, you have to use .attr() . 如果要更改属性,则必须使用.attr()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM