последовательные методы JS - PullRequest
2 голосов
/ 08 апреля 2011

У меня есть функция JS, которая выбирает некоторые элементы на основе параметров

function getElement() {
    var scope = document;

    this.by = function(data) {
        for (key in data) {
            if (key == 'id')    scope = scope.getElementById(data.id);
            if (key == 'tag')   scope = scope.getElementsByTagName(data.tag);
        }       
        return scope;
    }
}

function getEl(data) { return new getElement().by(data); }

Это называется как getEl(id : 'divId', tag : 'span') и выберет все промежутки в div 'divId'.

Теперь я хотел бы создать еще одну функцию (внутри функции Element), которая называется style, которая будет изменять CSS на всех ранее выбранных участках.

Что-то вроде

function getElement() {
    var scope = document;

    this.by = function(data) {
        for (key in data) {
            if (key == 'id')    scope = scope.getElementById(data.id);
            if (key == 'tag')   scope = scope.getElementsByTagName(data.tag);
        }       
        return scope;
    }

    this.style = function(data) {
        console.log(data);
    }
}

Я хотел бы иметь возможность сделать что-то вроде getEl({id : 'divId', tag : 'span').style({display : 'none'})

Но, похоже, это не работает, и я получаю getEl({id: "divId", tag: "span"}).style is undefined ошибку.

ps: это только для целей обучения, пожалуйста, не предлагайте jQuery или другие подобные фреймворки! :)

С уважением!

Ответы [ 2 ]

1 голос
/ 08 апреля 2011

getEl возвращает переменную scope, которая представляет собой список элементов DOM, а не ссылку на getElement. Вам нужно вернуть this, чтобы иметь возможность сделать что-то вроде new getElement().by(data).style().

this.by = function(data) {
    for (key in data) {
        if (key == 'id')    scope = scope.getElementById(data.id);
        if (key == 'tag')   scope = scope.getElementsByTagName(data.tag);
    }       
    return this;
}

Тогда вы можете сделать getEl({id : 'divId', tag : 'span'}).style({display : 'none'}).

Чтобы получить переменную scope, вы можете добавить что-то вроде этого:

this.elements = function(){
    return scope;
}

getEl({id : 'divId', tag : 'span'}).elements() вернет список элементов DOM.

0 голосов
/ 09 апреля 2011

Я разобрался, благодаря Rocket:)

function getElement() {
    this.scope = document;

    this.get = function() {
        return this.scope;
    }

    this.by = function(data) {
        for (key in data) {
            if (key == 'id')    this.scope = this.scope.getElementById(data.id);
            if (key == 'tag')   this.scope = this.scope.getElementsByTagName(data.tag);

        }
        return this;
    }

    this.style = function(data) {
        console.log(typeof(this.scope));
        for (key in data) {
            if (this.scope.length) {
                for (i = 0; i < this.scope.length; i++) {
                    this.scope[i].style[key] = data[key];
                }
            }
            else {
                this.scope.style[key] = data[key];
            }
        }
        return this;
    }
}
function getEl(data) { return new getElement().by(data); }

Работает с: getEl({id : "tara_content", tag : "div"}).style({display : "none"}); getEl({id : "tara_content"}).style({display : "none"}); getEl({tag : "div"}).style({display : "none"});

Как заметил Матиас Биненс, by() может возвращать массив элементов или только один элемент, поэтому в style() я проверяю длину this.scope. (Я не мог найти способ заставить тип).

Спасибо за помощь! :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...