代码之家  ›  专栏  ›  技术社区  ›  John

访问$('selector')。函数/对象中的数据

  •  2
  • John  · 技术社区  · 16 年前

    如何访问函数或对象中由$.data()设置的值

           $('#timers').data('firsttimer', 100);
    
    
        //prints 100
        document.write($('#timers').data('firsttimer'));
    
        function blah(){
            //Prints nothing
            document.write($('#timers').data('firsttimer'));
        }
    
    blah();
    

    http://jsfiddle.net/JUfd8/

    4 回复  |  直到 16 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    document.write() 在函数调用内部,但是如果使用jQuery的 .append() .

    function blah(){
        $('body').append($('#timers').data('firsttimer'));
    };
    

    找到这个关于 document.write :

    Why is document.write considered a "bad practice"?

    那篇文章中的一个答案中有一个有趣的句子:

    只要你不尝试在文档加载后使用它,document.write并不是天生的邪恶,在我看来。

    因此,这可能是问题的关键(或部分,无论如何)。

        2
  •  1
  •   zerkms    16 年前

    问题出在“document.write()”中。尽量避免。

        3
  •  1
  •   Goyuix    16 年前

    在本例中,我认为document.write以某种奇怪的方式在DOM上运行,清除了timers div。将document.write调用切换为alert调用(并添加一行调用blah())使我可以看到两个警报框,它们都显示值100。

    <div id="timers"></div>
    

    $('#timers').data('firsttimer', 100);
    
    //shows 100
    alert($('#timers').data('firsttimer'));
    
    function blah(){
      //Prints nothing
      alert($('#timers').data('firsttimer'));
    }
    
    blah();
    
        4
  •  1
  •   Anurag    16 年前

    并非所有浏览器的行为都是一致的。记住,在jsfiddle上,由于您选择了 onLoad 设置在左侧。加载DOM后,使用 document.write 将替换整个文档。

    以下是来自 HTML5 specs 在document.write上:

    除非在解析文档时从脚本元素的主体调用,或者在脚本创建的文档上调用,否则调用此方法将首先清除当前页,就像调用了document.open()一样。

    以下是浏览器在我的Mac上的行为 code

    Chrome和Safari
    把文件一笔勾销。即使100也没有打印出来。文本节点本身在这里被忽略,但是当包装在一些html标记中时,它们就会出现。 This code <b> <i> 分别标记。

    Opera和Firefox
    擦除文档,然后附加文本节点“100undefined”。它打印“未定义”,因为节点 <div id="timers></div>

    你打电话来 在Opera和Firefox上

    document.write($('#timers').data('firsttimer'));
    

    $('#timers').data('firsttimer') 首先求值,因为原始文档此时完好无损,所以我们得到值100,然后将其传递给 文档.写入 #timers 返回未定义的。