Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery data()不';我不能在全球范围内工作_Javascript_Jquery - Fatal编程技术网

Javascript jQuery data()不';我不能在全球范围内工作

Javascript jQuery data()不';我不能在全球范围内工作,javascript,jquery,Javascript,Jquery,我在jQuery本机方法中添加了两个函数,它们使用jQuery data()方法存储信息以检索后者 问题是,如果属性已经存储,我不想存储它 因此,我: $.fn.foo = function() { if(!$.hasData(this)) { $.data(this, 'width', this.css('width')); $('#test').append('foo : Added to "data"<br>'); } } $.f

我在jQuery本机方法中添加了两个函数,它们使用jQuery data()方法存储信息以检索后者

问题是,如果属性已经存储,我不想存储它

因此,我:

$.fn.foo = function() {
    if(!$.hasData(this)) {
        $.data(this, 'width', this.css('width'));
        $('#test').append('foo : Added to "data"<br>');
    }
}
$.fn.bar = function() {
    if(!$.hasData(this)) {
        $.data(this, 'width', this.css('width'));
        $('#test').append('bar : Added to "data"<br>');
    }
}

$('element').foo();
$('element').bar();
$.fn.foo=函数(){
如果(!$.hasData(此)){
$.data(this'width',this.css'width');
$('#test').append('foo:Added to“data”
'); } } $.fn.bar=函数(){ 如果(!$.hasData(此)){ $.data(this'width',this.css'width'); $('#test').append('bar:添加到“数据”
'); } } $('element').foo(); $('element').bar();
但它输出“添加到数据”两次,而不是一次。看起来,$.data()根本不起全局作用。我应该如何调整代码,以使数据表现出全局性

以下是JSFIDLE:

将dom元素引用作为其第一个参数,而不是jQuery对象。在插件方法
中,这个
将引用被调用的jQuery包装器对象,而不是dom元素引用

$.fn.foo=函数(){
//也返回此以保持可更改性
返回此值。每个(函数(){
如果(!$.hasData(此)){
$.data(this'width',$(this.css'width');
$('#test').append('foo:Added to“data”
'); } }) } $.fn.bar=函数(){ 返回此值。每个(函数(){ 如果(!$.hasData(此)){ $.data(this'width',$(this.css'width'); $('#test').append('bar:添加到“数据”
'); } }) } $('#element').foo(); $('#元素').bar()
我希望您以前的不太详细的answser只使用这个[0],我现在正在使用它,它工作得非常好!谢谢