Javascript文本字段

时间:2017-08-25 05:46:19

标签: javascript html

问题:

使用事件监听器,我希望单击按钮时,文本字段中的值会显示在相应的div中。 " [object HTMLInputElement]" 单击按钮时显示在div中。我认为textOne变量保存文本字段本身而不是其内容。我该如何解决这个问题?

html:

<form>
<input type="text" id="textOne" value="one"/><br>
<input type="text" id="textTwo" value="two"/><br>
<input type="button" id="btn" value="Enter"/><br>
textOne: <div id="one" style="width: 100px; height: 20px; border: 1px solid black;"></div><br>
textTwo: 
<div id="two" style="width: 100px; height: 20px; border: 1px solid black;"></div>
</form>

javascript:

var divOne = document.getElementById("one");
var divTwo = document.getElementById("two");
var textOne = document.getElementById("textOne");
var textTwo = document.getElementById("textTwo"); 
var btn = document.getElementById("btn");

function inDiv() {

    divOne.innerHTML = textOne;
    divTwo.innerHTML = textTwo;
}

btn.addEventListener("click", inDiv);

3 个答案:

答案 0 :(得分:1)

您需要访问他们的值。使用.value属性访问其值。使用getElementById,您可以获得整个HTMLElement作为对象,在您的情况下HTMLInputElement。您可以访问该对象的许多其他属性。

var divOne = document.getElementById("one");
var divTwo = document.getElementById("two");
var textOne = document.getElementById("textOne");
var textTwo = document.getElementById("textTwo"); 
var btn = document.getElementById("btn");

function inDiv() {

    divOne.innerHTML = textOne.value;
    divTwo.innerHTML = textTwo.value;
}

btn.addEventListener("click", inDiv);
<form>
<input type="text" id="textOne" value="one"/><br>
<input type="text" id="textTwo" value="two"/><br>
<input type="button" id="btn" value="Enter"/><br>
textOne: <div id="one" style="width: 100px; height: 20px; border: 1px solid black;"></div><br>
textTwo: 
<div id="two" style="width: 100px; height: 20px; border: 1px solid black;"></div>
</form>

答案 1 :(得分:0)

  

我认为textOne变量本身就是文本字段   而不是它的内容。

不,它没有。
<a>返回html元素输入本身 要获取其$gal_id = (int) $gallery[ $i ]; echo '<a href="' . esc_url( wp_get_attachment_url( $gal_id ) ) . '"</a> ,请参阅此输入的wp_get_attachment_url( $gal_id )属性:

document.getElementById("one");

答案 2 :(得分:0)

&#13;
&#13;
var one = document.getElementById("one");
var two = document.getElementById("two");
var inp1 = document.getElementById("textOne");
var inp2 = document.getElementById("textTwo");
var btn = document.getElementById("btn");
btn.addEventListener("click",function(){
one.innerHTML = inp1.value;
two.innerHTML = inp2.value;
})
&#13;
<form>
<input type="text" id="textOne" value="one"/><br>
<input type="text" id="textTwo" value="two"/><br>
<input type="button" id="btn" value="Enter"/><br>
textOne: <div id="one" style="width: 100px; height: 20px; border: 1px solid black;"></div><br>
textTwo: 
<div id="two" style="width: 100px; height: 20px; border: 1px solid black;"></div>
</form>
&#13;
&#13;
&#13;