我有一个非常简单的(一个会想到的)任务。jquery通过.data()不工作将值分配给键
将值传递给弹出窗口并基于点击(继续或取消)使用传递的值执行操作。
// on click we pass the value to the function testing - so far so good
$('#numbers').delegate('.icondelete', 'click', function(){
testing($(this).attr('data-options'));
});
我通过找到一个函数值,然后尝试将其分配到一个关键
function testing(id){
//we can see that it passed successfully
alert("here it is: " + id);
//push the data into key data-id
$('#dodelete').data('data-id',id);
//but this alert doesn't return the value
alert("it should be here shouldn't it? " + $('#dodelete').attr('data-id'));
}
HTML
<div id='numbers' >
<div class='icondelete' data-options='123' >Set data-options as 123 - click here to test</div>
</div>
<br><br>
<div id='dodelete' data-id=''>landing div</div>
如果检查出的小提琴http://jsfiddle.net/Microbe/cRLfC/4/,你可以看到该值传递给函数no probs,但是当我尝试将它分配给密钥时,它不会。
我哪里错了?
啊哈 - 就是这样。所以...你能解释为什么吗?我想.attr()返回该密钥的值 – Steve 2012-01-07 06:33:20
'.attr()'返回对象的属性值。 '.data()'不会将其数据存储为对象的属性 - 它将其存储在内部缓存中 - 因此您不能使用'.data()'进行设置,并使用'.attr()'进行读取。你用'.data(key,value)'设置东西,你用'.data(key)'读取它们。这就是jQuery'.data()'的工作原理。 – jfriend00 2012-01-07 06:43:22
灯亮起来!谢谢! – Steve 2012-01-07 06:51:47