console.log没有控制输出值

时间:2017-04-25 12:50:15

标签: javascript html console.log

console.log没有控制输出值,但它表明它已存在,它只是因为某种原因而无法访问。与警报功能相同。您可以在控制台中测试代码,您将看到输出确实存在,但是为空。

代码:

(function () {
var button = document.getElementsByTagName("button");
var userInput = document.getElementById("user_input").value;
button[0].addEventListener("click", function () {
  console.log(userInput);
}, false);

})();

HTML:

<form>
    <input id="user_input" type="text" placeholder="add new task">
    <button type="button">
      <!-- SVG add icon-->
        <svg class="add_symbol" xmlns="http://www.w3.org/2000/svg" viewBox="1197.5 116.5 18 18">
          <defs>
            <style>
              .cls-1, .cls-2 {
                fill: none;
              }

              .cls-1 {
                stroke: #fff;
              }

              .cls-2 {
                stroke: #fcfeff;
              }
            </style>
          </defs>
          <g id="Group_3" data-name="Group 3" transform="translate(890 21)">
            <line id="Line_4" data-name="Line 4" class="cls-1" y2="18" transform="translate(316.5 95.5)"/>
            <line id="Line_5" data-name="Line 5" class="cls-2" y2="18" transform="translate(325.5 104.5) rotate(90)"/>
          </g>
        </svg>

    </button>
  </form>

console ss enter image description here

1 个答案:

答案 0 :(得分:3)

您在加载文档时获得了值。此时,该值为空。您需要在点击事件中获取值

(function() {
  var button = document.getElementsByTagName("button");
  var userInput = document.getElementById("user_input"); //Get only the element
  button[0].addEventListener("click", function() {
    console.log(userInput.value); //Get the value
  }, false);

})();
<form>
  <input id="user_input" type="text" placeholder="add new task">
  <button type="button">
      <!-- SVG add icon-->
        <svg class="add_symbol" xmlns="http://www.w3.org/2000/svg" viewBox="1197.5 116.5 18 18">
          <defs>
            <style>
              .cls-1, .cls-2 {
                fill: none;
              }

              .cls-1 {
                stroke: #fff;
              }

              .cls-2 {
                stroke: #fcfeff;
              }
            </style>
          </defs>
          <g id="Group_3" data-name="Group 3" transform="translate(890 21)">
            <line id="Line_4" data-name="Line 4" class="cls-1" y2="18" transform="translate(316.5 95.5)"/>
            <line id="Line_5" data-name="Line 5" class="cls-2" y2="18" transform="translate(325.5 104.5) rotate(90)"/>
          </g>
        </svg>

    </button>
</form>