结果返回[object HTMLInputElement]

时间:2017-11-29 08:12:14

标签: javascript html string dom

JS代码

'use strict';

$(document).ready(function() {
});

function change() {
    document.getElementById('the-name').innerHTML = document.getElementById('name');
}

HTML代码

<p> What's your name? <input type="text" placeholder="Name" id = "name"></input></p>

<button id="button" onclick= "change(document.getElementById('name'))"> Answer </button>

<p>Hello <span id = "the-name"></span>,</p>

使用上面的代码,每当我尝试通过单击按钮运行它时,我会在标题中得到结果。有人能通过告诉我我做错了什么来指出正确的方向吗?非常感谢,谢谢!

2 个答案:

答案 0 :(得分:3)

您的问题是,您要为{@ 1}}元素分配HTMLInputElement而不是innerHTMLtext

HTML content

您需要获取输入值:

document.getElementById('the-name').innerHTML = document.getElementById('name');

<强>演示:

document.getElementById('the-name').innerHTML = document.getElementById('name').value;
'use strict';

$(document).ready(function() {});

function change() {
  document.getElementById('the-name').innerHTML = document.getElementById('name').value;
}

答案 1 :(得分:1)

您正在将整个HTML输入元素分配给<!DOCTYPE html> <html> <head> <title></title> </head> <body> <span>Total Score: </span> <span id="totalScore"></span> <form id="myForm"> <fieldset class="article"> <h3><legend>Eligibility Test</legend></h3> </fieldset> <fieldset class="article"> <legend>Have you had your record expunged before?</legend> <input type="radio" name="field1" value="0" onclick="getscores1(this)"> <label>Yes</label> <input type="radio" name="field1" value="1" onclick="getscores1(this)"> <label>No</label> </fieldset> <fieldset class="article"> <legend>Do you have any charges pending against you?</legend> <input type="radio" name="field2" value="0" onclick="getscores2(this)"> <label>Yes</label> <input type="radio" name="field2" value="1" onclick="getscores2(this)"> <label>No</label> </fieldset> <fieldset> <legend>Is your drivers license suspended?</legend> <input type="radio" name="field3" value="0" onclick="getscores3(this)"> <label>Yes</label> <input type="radio" name="field3" value="1" onclick="getscores3(this)"> <label>No</label> </fieldset> <fieldset id="submitbutton" class="article"> <input type="button" id="submit" value="submit"> <!-- Don't do this: onclick="location.href ='testSite.html';" --> </fieldset> </form> </body> <script> var s1, s2, s3; [s1, s2, s3] = [0, 0, 0]; document.getElementById("submit").onclick = function () { //location.href = "testSite.html"; //JavaScript context is on the client side for the current page only. When you reload the page, it gets recreated, all variables are re-initialized. answer(s1, s2, s3); }; function getscores1(score1) { s1 = score1.value; } function getscores2(score2) { s2 = score2.value; } function getscores3(score3) { s3 = score3.value; } function answer(score1, score2, score3) { if (score1 == 0 || score2 == 0 || score3 == 0) { document.getElementById('totalScore').innerHTML = "false"; } else{ document.getElementById('totalScore').innerHTML = "pass"; } } </script> </html>

您必须使用HTML-Input Element的value属性来获取其值。

<span>