简体   繁体   中英

How can I make JS objects into jQuery elements?

I'll admit that I don't really know what I'm doing. But I'm trying to work with JS in an OO way.

I have a form field where I input data. On the right side I have a "preview" of how the special offer will look like.

As I add text in the input fields, I want it to show in the preview.

I've tried using the following code, but I'm not being very successful. I think there are some basic knowledge / understanding I'm missing here.

mirrorText: function(){
    var self = this;
    $('#title').keyup(function(){
        self.previewObject.title.text($(this).val());
     });
},

previewObject: {
    img: null,
    title: null,
    dateRange: null,
    address: null,

    init: function(){
        self.img = $('.offer-container .promo-img');
        self.title = $('.offer-container h3');
        self.dateRange = $('.offer-container .valid-through');
    }
}

See the full code here (jsfiddle).

You can't have DIVs inside a P (paragraph) so the elements were not found. I changed that to another div for the example.

You also referenced self in one place where I think it should have been this (inside init).

JSFiddle: http://jsfiddle.net/TrueBlueAussie/w0nn5Ls9/6/

Promo = {

    init: function(){
        var self = this;
        self.previewObject.init();
        self.mirrorText();
    },

    mirrorText: function(){
        var self = this;
        $('#title').keyup(function(){
            self.previewObject.title.html($(this).val());
         });
    },

    previewObject: {
        img: null,
        title: null,
        dateRange: null,
        address: null,

        init: function(){
            this.img = $('.offer-container .promo-img');
            this.title = $('.offer-container h3');
            this.dateRange = $('.offer-container .valid-through');
        }
    }
}    

Promo.init();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM