如何在HTHML中打印所选项目下拉列表

时间:2016-11-12 14:00:15

标签: javascript

function myfun() {
  var x = document.getElementById('state').selectedIndex;
  var text = document.getElementsByTagName("option")[x].value;
  document.getElementById("pr").innerHTML = text;
}

在此代码中document.getElementsByTagName("option")[x].value获取下拉列表中的值,document.getElementById("pr").innerHTML = text<div id="pr">标记中打印此值。但是,价值不是印刷品。为什么呢?

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:使用text代替value example

&#13;
&#13;
function myfun() {
  var x = document.getElementById('state').selectedIndex;
  var text = document.getElementsByTagName("option")[x].text;//its a text
  document.getElementById("pr").innerHTML = text;
}
myfun();
&#13;
<select id="state" onchange="myfun()">
  <option value="hi">hi</option>
  <option value="hello">hello</option>
</select> 
<p id="pr"></p>
&#13;
&#13;
&#13;

<强>交替

function myfun() {
 var x = document.getElementById('state').value;
  document.getElementById("pr").innerHTML = x
}

答案 1 :(得分:0)

function myfun() {
  var x = document.getElementById('state').selectedIndex;
  var text = document.getElementsByTagName("option")[x].text;//its a text
  document.getElementById("pr").innerHTML = text;
}
myfun();
<select id="state" onchange="myfun()">
  <option value="hi">hi</option>
  <option value="hello">hello</option>
</select> 
<p id="pr"></p>