2012-04-05 8 views
0

"コンテキスト"の問題に遭遇していると思います。オブジェクトの「参照」を操作しようとすると、Javascript/jQueryスコープとコンテキストの問題が発生する

ページ上のすべての画像のソースを削除します。私は各画像のオブジェクトの配列を構築しています。ソースを隠すと、元のオブジェクトのプロパティに影響を与えずに、変更がリアルタイムに表示されるようにします。私は、クリックイベントで(画面上の)画像を操作したい。

例えば

:私も内のオブジェクトのメソッドを構築しようとしている

$('#imagesOff').click(function(){ 
    for (i=0; i<aryImageObjects.length; i++) { 
     aryImageObjects[i].objImg.replaceWith('hrm'); 
    }; 
}); //end imagesOff click function 

$('#moz_iframe').contents().find("img").each(function(index){ 
    aryImageObjects.push(new imageObject($(this), $('#iframeHolder'))); 
}); //end each 

...

function imageObject(objImg, objHolder) { 
    this.objImg = objImg; 
    this.imgSrc = objImg.attr('src'); 
    //this.objImg.replaceWith('hrm'); <-- this works just fine in this context 
}; //end constructor 

... が、これは動作しません。私の元のコンストラクタ:

this.hideImages = function() { 
    this.objImg.replaceWith('hrm'); 
    }; 
...

$('#imagesOff').click(function(){ 
    for (i=0; i<aryImageObjects.length; i++) { 
     aryImageObjects[i].hideImages(); 
    }; 
}); //end imagesOff click function 

しかし、それはどちらか動作するようには思えません。

任意の助けをいただければ幸いです:)

+0

をので、あなたがそのイメージのソースを変更しかし、それは元のソースです維持したいと言いますか? – Joseph

答えて

1

here's what i've come up

$(function() { 

    //reference array 
    var ref = []; 

    (function() { 

     //get each image and reference the element and store source 
     $('img').each(function() { 
      var newImg = {}; 
      newImg.el = this; //storing the DOM element instead of a jQuery object 
      newImg.src = this.src; 
      ref.push(newImg); 
     }); 
    }()); 

    //if the element is clicked, replace using the reference in the array 
    $('img').on('click', function() { 
     for (i = 0; i < ref.length; i++) { 

      //wrap reference in jQuery, and operate 
      $(ref[i].el).replaceWith('hrm'); 
     }; 

     //img still here even after DOM was replaced 
     console.log(ref); 
    }); 
});​ 
+0

ジョセフ、ありがとう、これは違いを知る上での良いレッスンです。 DOM要素とjQueryオブジェクトへの参照を格納します。しかし、実際には私の検索でコードが機能していなかったことが判明しました。バックグラウンドの属性(TD)を取り除くためにbody要素全体を置換していました。元のDOMを本質的に再構築していました。あなたの助けと洞察にとても感謝します! – marcy23

関連する問題