如何访问函数或对象内 $.data() 设置的值
$('#timers').data('firsttimer', 100);
//prints 100
document.write($('#timers').data('firsttimer'));
function blah(){
//Prints nothing
document.write($('#timers').data('firsttimer'));
}
blah();
请参阅此 jsfiddle 以轻松访问测试代码 http://jsfiddle.net/JUfd8/
最佳答案
由于某种原因,我在函数调用中遇到 document.write()
问题,但如果我使用 jQuery 的 .append()
,它就可以正常工作。
function blah(){
$('body').append($('#timers').data('firsttimer'));
};
编辑:
发现有关 document.write
的 stackoverflow 问题:
Why is document.write considered a "bad practice"?
该帖子的一个答案中的一个有趣的句子:
在我看来,只要您在文档加载后不尝试使用它,document.write 本质上并不是邪恶的。
所以这可能是问题的关键(或者至少是问题的一部分)。
关于javascript - 访问函数/对象中的 $ ('selector' ).data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2894113/