从另一个函数获取或设置变量

时间:2015-12-18 23:29:52

标签: javascript

我正在使用this custom JavaScript range slider,我希望能够获取并设置滑块值。我已经实现了集合function。 (如果你有更好的方法,请告诉我。)我在实施getValue function

时遇到了问题

我尝试了以下操作:

function getValue() {
    if (value) {
        return value;
    }
    return;
}

当我调用该函数时,我收到以下错误:

  

未捕获的ReferenceError:未定义getValue

创建全局变量不是一种选择。如何获得滑块值?

要设置或获取滑块值,我希望能够执行以下操作:

mySlider.Value = 17;              // Set Value
var currentValue = mySlider.Value // Get Value

JSFiddle



function rangeSlider(elem, config, update) {

  if (typeof update != "undefined" && update) {
    var dragger = elem.getElementsByTagName('span')[0];
    var range = elem.getElementsByTagName('div')[0];
    var isVertical = config.vertical;
    var rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    var rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop'];
    var draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    dragger.style[!isVertical ? 'left' : 'top'] = (config.value / 100 * rangeWidth - (draggerWidth / 2)) + 'px';
    return;
  }

  function getValue() {
    if (value) {
      return value;
    }
    return;
  }

  var html = document.documentElement,
    range = document.createElement('div'),
    dragger = document.createElement('span'),
    down = false,
    rangeWidth, rangeOffset, draggerWidth, cachePosition;

  var defaults = {
    value: 0, // set default value on initiation from `0` to `100` (percentage based)
    vertical: false, // vertical or horizontal?
    rangeClass: "", // add extra custom class for the range slider track
    draggerClass: "", // add extra custom class for the range slider dragger
    drag: function(v) { /* console.log(v); */ } // function to return the range slider value into something
  };

  for (var i in defaults) {
    if (typeof config[i] == "undefined") config[i] = defaults[i];
  }

  function addEventTo(el, ev, fn) {
    if (el.addEventListener) {
      el.addEventListener(ev, fn, false);
    } else if (el.attachEvent) {
      el.attachEvent('on' + ev, fn);
    } else {
      el['on' + ev] = fn;
    }
  }

  var isVertical = config.vertical;

  elem.className = (elem.className + ' range-slider ' + (isVertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
  range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
  dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");

  addEventTo(range, "mousedown", function(e) {
    html.className = (html.className + ' no-select').replace(/^ +/, "");
    rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop'];
    draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    down = true;
    updateDragger(e);
    return false;
  });

  addEventTo(document, "mousemove", function(e) {
    updateDragger(e);
  });

  addEventTo(document, "mouseup", function(e) {
    html.className = html.className.replace(/(^| )no-select( |$)/g, "");
    down = false;
  });

  addEventTo(window, "resize", function(e) {
    var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    dragger.style[!isVertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px';
    down = false;
  });

  function updateDragger(e) {
    e = e || window.event;
    var pos = !isVertical ? e.pageX : e.pageY;
    if (!pos) {
      pos = !isVertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) {
      dragger.style[!isVertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px';
      cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100);
      config.drag(cachePosition);
    }
  }

  function initDragger() {
    var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    cachePosition = ((config.value / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']);
    dragger.style[!isVertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';
    config.drag(config.value);
  }

  range.appendChild(dragger);
  elem.appendChild(range);

  initDragger();

}

var slid1 = document.getElementById('range-slider-1');
var btn = document.getElementById('btn');
var anotherBtn = document.getElementById('anotherBtn');
var resultP = document.getElementById('results');

rangeSlider(slid1, {
  value: 10,
});
btn.onclick = function() {
  rangeSlider(slid1, {
    value: 50
  }, 1);
}

anotherBtn.onclick = function() {
  document.getElementById('results').innerHTML = "Your Current Value is: " + getValue();
}
&#13;
.range-slider-track {
  height: 20px;
}
.range-slider-track:before {
  content: "";
  display: block;
  width: 100%;
  height: 2px;
  background-color: black;
}
.range-slider-track .dragger {
  display: block;
  width: 10px;
  height: inherit;
  position: relative;
  background-color: red;
}
&#13;
<div id="range-slider-1"></div>
<button id="btn">Set Value</button>
<button id="anotherBtn">Get Value</button>
<p id="results"></p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

函数“rangeSlider()”应作为对象处理,而不是作为函数处理......

您必须创建一个对象:

var mySlider = new rangeSlider(slid1, { value: 10,});

你可以获得它的价值:

mySlider.getValue()

看看:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

答案 1 :(得分:1)

将此javascript粘贴到原始小提琴中并将其设置为正常工作:

function rangeSlider(elem, config, update) {
    var this_ = this;

    this.setValue = function(value) {
        var dragger = this.config.elem.getElementsByTagName('span')[0];
        var range = this.config.elem.getElementsByTagName('div')[0];
        var rangeWidth = range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        var draggerWidth = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        dragger.style[!this.config.vertical ? 'left' : 'top'] = (value / 100 * rangeWidth - (draggerWidth / 2)) + 'px';
        this.config.value = value;
    };

    this.getValue = function() {
        return this.config.value;
    };

    var html = document.documentElement,
        range = document.createElement('div'),
        dragger = document.createElement('span'),
        down = false,
        rangeWidth, rangeOffset, draggerWidth, cachePosition;

    this.config = {
        value: (config.value || 0), // set default value on initiation from `0` to `100` (percentage based)
        vertical: (config.vertical || false), // vertical or horizontal?
        rangeClass: "", // add extra custom class for the range slider track
        draggerClass: "", // add extra custom class for the range slider dragger
        drag: function(v) { /* console.log(v); */ }, // function to return the range slider value into something
        elem: elem
    };

    addEventTo = function(el, ev, fn) {
        if (el.addEventListener) {
            el.addEventListener(ev, fn, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + ev, fn);
        } else {
            el['on' + ev] = fn;
        }
    }

    elem.className = (elem.className + ' range-slider ' + (this.config.vertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
    range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
    dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");

    addEventTo(range, "mousedown", function(e) {
        html.className = (html.className + ' no-select').replace(/^ +/, "");
        rangeWidth = range[!this_.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        rangeOffset = range[!this_.config.vertical ? 'offsetLeft' : 'offsetTop'];
        draggerWidth = dragger[!this_.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        down = true;
        updateDragger(e);
        return false;
    });

    addEventTo(document, "mousemove", function(e) {
        updateDragger(e);
    });

    addEventTo(document, "mouseup", function(e) {
        html.className = html.className.replace(/(^| )no-select( |$)/g, "");
        down = false;
    });

    addEventTo(window, "resize", function(e) {
        var woh = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        dragger.style[!this.config.vertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px';
        down = false;
    });

    function updateDragger(e) {
        e = e || window.event;
        var pos = !this_.config.vertical ? e.pageX : e.pageY;
        if (!pos) {
            pos = !this_.config.vertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) {
            dragger.style[!this_.config.vertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px';
            cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100);
            this_.config.value = cachePosition;
            this_.config.drag(cachePosition);
        }
    };

    this.initDragger = function() {
        var woh = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        cachePosition = ((config.value / 100) * range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight']);
        dragger.style[!this.config.vertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';
        this.config.drag(this.config.value);
    };

    range.appendChild(dragger);
    elem.appendChild(range);

    this.initDragger();

}

var slid1 = document.getElementById('range-slider-1');
var btn = document.getElementById('btn');
var anotherBtn = document.getElementById('anotherBtn');
var resultP = document.getElementById('results');

var rs = new rangeSlider(slid1, {
    value: 10,
});

var slid2 = document.getElementById('range-slider-2');
var rs2 = new rangeSlider(slid2, {
    value: 20,
});


btn.onclick = function() {
    rs.setValue(50);
}
anotherBtn.onclick = function() {
    document.getElementById('results').innerHTML = "Range 1: " + rs.getValue() + '<br/>Range2: ' + rs2.getValue();
}

这个HTML也是:

<div id="range-slider-1"></div>
<button id="btn">Set Value</button>
<button id="anotherBtn">Get Value</button>
<div id="range-slider-2"></div>
<p id="results"></p>

像其他一些海报所说的那样,你需要稍微修改一下你的功能。 我没有时间清理新代码,但我相信你会明白这个想法。 以下是一些需要注意的事项:

  1. 您想通过调用new rangeSlider来创建新对象。
  2. 您可以将新对象分配给变量,以便您可以使用该变量来设置或获取值。
  3. 请注意var this_ = this语句,这样我们就可以访问对象实例甚至某些事件,因为这些事件中的这些事件可能是DOM中的实际元素。
  4. 这种新方法支持文档中的多个滑块,与原始代码一样,但获取和设置值更简单,更简洁。
  5. 我确定我们可以更多地清理这些代码,所以尽情享受。