如何在没有更改函数

时间:2018-01-15 14:34:07

标签: javascript jquery html css select

我当前有一个标签,显示动态选择下拉列表中的选定选项,但它只显示onchange。我希望能够在页面加载时显示当前值。我尝试过切换'更改'为了加载'没有运气。这是我目前的设置: 
 
 Array.prototype.forEach.call(document.getElementsByName(' filename'),function(elem){
   elem.addEventListener('更改',function(){
     document.getElementById(' mylabel')。innerHTML = this.value;
   });
 });
 < select class =" select1"命名="文件名" ID ="文件名">
   <选项> FOO< /选项>
   <选项>巴≤; /选项>
 < /选择>
 < label id =" mylabel">< / label>
 
 

5 个答案:

答案 0 :(得分:1)

你确实说过页面加载的时候,它就像这样简单......

<body onload="mylabel.innerHTML=filename.value;">

答案 1 :(得分:0)

我希望这是你想要的,我只是在功能之外添加了一行

Array.prototype.forEach.call(document.getElementsByName('filename'), function(elem) {
  elem.addEventListener('change', function() {
    document.getElementById('mylabel').innerHTML = this.value;
  });
});
document.getElementById('mylabel').innerHTML = document.getElementById('filename').value;
<select class="select1" name="filename" id="filename">
  <option>foo</option>
  <option>bar</option>
</select>
<label id="mylabel"></label>

答案 2 :(得分:0)

&#13;
&#13;
Array.prototype.forEach.call(document.getElementsByName('filename'), function(elem) {
  elem.addEventListener('change', function() {
    document.getElementById('mylabel').innerHTML = this.value;
  });
});

$('#mylabel').html($('#filename').val());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="select1" name="filename" id="filename">
  <option>foo</option>
  <option>bar</option>
</select>
<label id="mylabel"></label>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

为什么要循环?

&#13;
&#13;
let e = document.getElementById("filename");
let x = document.getElementById('mylabel');

document.addEventListener('DOMContentLoaded',function(){
   x.innerHTML = e.value;    
   e.addEventListener('change', function(){
      x.innerHTML = this.value;
   });
});
&#13;
<select class="select1" name="filename" id="filename">
  <option>foo</option>
  <option>bar</option>
</select>
<label id="mylabel"></label>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

应用DRY(不要自己重复):命名单击处理程序,然后在初始化期间手动调用它。或者,您也可以在初始化期间手动触发更改。

$(function() {
  // event handler on change
  $('#filename').change(mylabel_update);

  // update mylabel to show filename
  function mylabel_update() {
    $('#mylabel').html($('#filename').value);
  } 

  // initialize option A - call the function directly
  mylabel_update();

  // initialize option B - force the change event (don't need the named fn)
  $('#filename').trigger('change');
});