Javascript/jQuery 范围和上下文问题,当试图操作对象的“引用”时

Javascript/jQuery Scoping and Context Issue when trying to manipulate the "reference" of an object

本文关键字:对象 操作 引用 范围 jQuery 上下文 问题 Javascript      更新时间:2023-09-26

我想我遇到了一个"上下文"问题,希望有人能在这个问题上有更多的了解。

我想删除页面上所有图像的来源。 我为每个图像构建了一个对象数组。 当我隐藏源时,我希望更改实时显示,而不会影响我的原始对象属性。 我想在点击事件上操作图像(在屏幕上)。

例如:

$('#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

。但这不起作用:

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

我还尝试在原始构造函数中构建一个对象方法:

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

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

但这似乎也行不通。

任何帮助将不胜感激:)

这是我

提出的

$(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);
    });
});​