输出标题元素的JavaScript函数

时间:2018-04-03 23:39:21

标签: javascript forms html-heading

您好我是初学者,并希望得到一些帮助。我怎样才能使addHeading()从下拉框中获取标题类型和从表单中获取文本,并创建/输出相应的标题元素?截至目前,它只输出文本而不是具有相应大小的实际标题。这是我到目前为止所拥有的。我无法在此找到具体的例子或任何内容。提前谢谢。

function addHeading() {
    var x = document.getElementById("heading");
    var headingText =
        document.getElementById("headingText").value;

    document.getElementById("divHeading").innerHTML = headingText;
}

function clearHeading() {
    document.getElementById('divHeading').innerHTML = headingText = [];
}
form {
  width: 500px;
  margin: 0px auto;
  border: 1px solid khaki;
  background-color: antiquewhite;
  border-collapse: collapse;
  padding: 10px;
  margin-bottom: 20px;
}
form h2 {
  margin: 0;
}
input {
  margin: 5px;
}
<form id='headingForm'>
  <h2>Heading Form</h2>
  <span>Heading Type:</span>
  <select id='heading' name='heading'>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
   </select>
  <br>
  <span>Text:</span>
  <input required='required' type='text' name='headingText' 
id='headingText'>
  <br>
  <input type='button' value='Add Heading' onclick='addHeading()'>
  <input type='button' value='Clear Heading' onclick='clearHeading()'>
  <div id='divHeading'></div>
</form>

1 个答案:

答案 0 :(得分:0)

希望这有助于FIDDLE

function addHeading(){
    var x = document.getElementById("heading").value;
    var headingText = document.getElementById("headingText").value;
    document.getElementById("divHeading").innerHTML = '<h'+x+'>'+headingText+'</h'+x+'>';
}

function clearHeading() {
    document.getElementById('divHeading').innerHTML = '';
    //document.querySelector('#headingText').value = '';
}
form {
    width: 500px;
    margin: 0px auto;
    border: 1px solid khaki;
    background-color: antiquewhite;
    border-collapse: collapse;
    padding: 10px;
    margin-bottom: 20px;
}
form h2 {
    margin: 0;
}
input {
    margin: 5px;
}
<form id='headingForm'>
    <h2>Heading Form</h2>
    <span>Heading Type:</span>
    <select id='heading' name='heading'>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
        <option value='4'>4</option>
    </select>
    <br>
    <span>Text:</span>
    <input required='required' type='text' name='headingText' id='headingText'>
    <br>
    <input type='button' value='Add Heading' onclick='addHeading()'>
    <input type='button' value='Clear Heading' onclick='clearHeading()'>
    <div id='divHeading'></div>
</form>