更有效的复制代码的方法

时间:2018-02-19 23:43:20

标签: javascript html

每次单击+按钮,我都希望显示相同的输入

So it looks like this

我在这里的方式工作正常,但似乎是最糟糕的方式,只是重复相同的代码和更改ID(如果我想要例如5输入,我将不得不重复此代码5次)。什么是更好的方法呢?

<html>
<head>

 <script language='JavaScript' type='text/javascript'>

    function show3(){
    document.getElementById('div2').style.display = 'block';
     }


</script>

<style>

   .hide {
   display: none;
   }

</style>
</head>
<body>

<div>

    <input type="range" min="0" max="1500" value="0" class="slider2" id="one"/>

    <p>Value(mm): <input type="text" id="two" size="10" class="special" /></p>

    <button onclick="show3();" type="button">+</button>


</div> 

<script>
    var slider1 = document.getElementById("one");
    var output2 = document.getElementById("two");
    output2.value = slider1.value;

    slider1.oninput = function() {
    output2.value = this.value;
    }
</script>


<div id="div2" class="hide">

    <input type="range" min="0" max="1500" value="0" class="slider2" id="three"/>

    <p>Value(mm): <input type="text" id="four" size="10" class="special" /></p>

    <button onclick="show3();" type="button">+</button>


</div> 

<script>
    var slider2 = document.getElementById("three");
    var output3 = document.getElementById("four");
    output2.value = slider1.value;

    slider2.oninput = function() {
    output3.value = this.value;
    }
</script>



</body>
</html>

&#13;
&#13;
<html>
<head>



<script language='JavaScript' type='text/javascript'>

	function show3(){
	  document.getElementById('div2').style.display = 'block';
	}


</script>
<style>
	.hide {
  display: none;
	}
</style>
</head>
<body>




	<div>
	
	<input type="range" min="0" max="1500" value="0" class="slider2" id="one"/>

	    <p>Value(mm): <input type="text" id="two" size="10" class="special" /></p>
	
		<button onclick="show3();" type="button">+</button>


	</div> 
	
	<script>
	var slider1 = document.getElementById("one");
	var output2 = document.getElementById("two");
	output2.value = slider1.value;

	slider1.oninput = function() {
	  output2.value = this.value;
	}
	</script>

	
		<div id="div2" class="hide">
	
	<input type="range" min="0" max="1500" value="0" class="slider2" id="three"/>

	    <p>Value(mm): <input type="text" id="four" size="10" class="special" /></p>
	
		<button onclick="show3();" type="button">+</button>


	</div> 
	
	<script>
	var slider2 = document.getElementById("three");
	var output3 = document.getElementById("four");
	output2.value = slider1.value;

	slider2.oninput = function() {
	  output3.value = this.value;
	}
	</script>



</body>
</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

这适用于所有滑块。但是你需要记住以下几点:

  1. 这只适用于已经在DOM中呈现的滑块(即使它们是隐藏的)如果你向DOM渲染新的滑块,你需要像在foreach循环中那样附加事件监听器。 / LI>
  2. 输入ID(例如“one”)需要与输出data-range="one"
  3. 匹配

    function show3(){
      document.getElementById('div2').style.display = 'block';
    }
    
    var sliders = document.querySelectorAll(".slider"); // slider = common class name
    sliders.forEach(( slider ) => {
      slider.addEventListener('input', (e) => {
        const sliderId = e.target.id;
        const output = document.querySelector(`[data-range=${sliderId}]`);
        output.value = e.target.value;
      });
    });
    <html>
    <head>
    <style>
       .hide {
         display: none;
       }
    </style>
    </head>
    <body>
    
    <div>
        <input type="range" min="0" max="1500" value="0" class="slider" id="one"/>
        <p>Value(mm): <input type="text" data-range="one" id="two" size="10" class="special" /></p>
        <button onclick="show3();" type="button">+</button>
    </div> 
    
    <div id="div2" class="hide">
    
        <input type="range" min="0" max="1500" value="0" class="slider" id="two"/>
        <p>Value(mm): <input type="text" data-range="two" id="four" size="10" class="special" /></p>
        <button onclick="show3();" type="button">+</button>
    
    </div> 
    </body>
    </html>

答案 1 :(得分:0)

可能更容易将代码包含在元素中并克隆它(parentNode是div):

<div>
    <input type="range" min="0" max="1500" value="0" 
      oninput="this.parentNode.getElementsByTagName('INPUT')[1].value = this.value"/>
    <p>Value(mm): <input type="text" size="10" /></p>
    <button type="button" 
      onclick="this.parentNode.parentNode.append(this.parentNode.cloneNode(true))">+</button>
</div>

答案 2 :(得分:0)

我建议您创建某种类,让您动态创建滑块组件。

这是一个快速示例(未优化):

var SliderComponent = (function(doc) {
  var defaults = {
    containerSelector: 'body',
    value: 0,
    min: 0,
    max: 1500,
    inputSize: 10,
    inputClass: 'special',
    sliderClass: 'slider',
    buttonClass: 'button'
  }, options;

  function SliderComponent(options) {
    options = Object.assign({}, defaults, options || {});
    this.container = getContainer(options);
    this.input = createInput(options);
    this.slider = createSlider(options);
    this.removeButton = createButton(options.buttonClass, '-');
    this.addButton = createButton(options.buttonClass, '+');
    this.element = render.apply(this);
    this.events = [];
    
    this.events.push(
      addEventListener.call(this, 'click', this.removeButton, function() {
        this.destroy();
      }),
      addEventListener.call(this, 'click', this.addButton, function() {
        new SliderComponent(options);
      }),
      addEventListener.call(this, 'input', this.slider, function(event) {
        this.input.value = event.target.value;
      }),
      addEventListener.call(this, 'input', this.input, function(event) {
        this.slider.value = event.target.value;
      })
    )
  }
  
  SliderComponent.prototype.destroy = function() {
    this.events.forEach(function(e) {
      e();
    });
    this.element.remove();
  }
  
  function addEventListener(name, element, listener) {
    listener = listener.bind(this);
    element.addEventListener(name, listener);
    return function() {
      element.removeEventListener(name, listener);
    };
  } 
  
  function getContainer(options) {
    var container = doc.querySelector(options.containerSelector);
    if(!container) {
      throw new Error('Container for selector %s not found', options.containerSelector);
    }
    return container;
  }
  
  function createInput(options) {
    var input = doc.createElement('input');
    input.setAttribute('type', 'number');
    input.setAttribute('min', options.min);
    input.setAttribute('max', options.max);
    input.setAttribute('size', options.inputSize);
    input.classList.add(options.inputClass);
    input.value = options.value;
    return input;
  }
  
  function createSlider(options) {
    var input = doc.createElement('input');
    input.setAttribute('type', 'range');
    input.setAttribute('min', options.min);
    input.setAttribute('max', options.max);
    input.classList.add(options.sliderClass);
    input.value = options.value;
    return input;
  }
  
  function createButton(klass, text) {
    var button = doc.createElement('button');
    button.setAttribute('type', 'button');
    button.classList.add(klass);
    button.textContent = text;
    return button;
  }
  
  function render() {
    var element = doc.createElement('div');
    element.appendChild(this.slider);
    element.appendChild(this.input);
    element.appendChild(this.removeButton);
    element.appendChild(this.addButton);
    return this.container.appendChild(element);
  }
  
  return SliderComponent;
})(document);

var sliders = new SliderComponent();