Javascript根据输入和长度更改标签innerHTML

时间:2017-04-07 01:07:36

标签: javascript

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><script type="text/javascript">
    function echoinputdatahere(elem){
    var size = elem.value.length;
    if(var size value.length == 0){
        document.getElementById("ef1").innerHTML = "Default_Text";
    }
    if( size value.length > 0){
        document.getElementById("ef1").innerText = 
    document.getElementById("inputdatahere").value;
    }
</script>
<style></style></head><body><form action="#">
<fieldset>
<legend id="ef1">Default_Text</legend>
<input
    type="text"
    id="inputdatahere"
            onkeypress="echoinputdatahere(this)">
</fieldset></form></body></html>

...

我尝试编码的内容如下。我希望id="inputdatahere" onkeypress中的文字仅在innerText的长度时将id="ef1"传奇id="inputdatahere"更改为id="inputdatahere"中的值{}大于0.否则如果id="inputdatahere"的长度为0,则将innerText的{​​{1}}恢复为id="ef1"

请告知。

3 个答案:

答案 0 :(得分:1)

使用oninput事件 - 有人可以粘贴文本到该字段中,对吧? :)你想处理所有案件!

另外简化您的代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">

  <script>
    function echoinputdatahere(elem) {
    
      var val = elem.value;
      var size = val.length;
      
      document.getElementById("ef1").innerHTML = size>0 ? val : "Default_Text";
    }
  </script>

</head>
<body>

  <form action="#">
    <fieldset>
      <legend id="ef1">Default_Text</legend>
      <input type="text" id="inputdatahere" oninput="echoinputdatahere(this)">
    </fieldset>
  </form>

</body>
</html>

答案 1 :(得分:0)

function echoinputdatahere(){
  var data = document.getElementById("inputdatahere").value;
  if(data.length > 1 )
    document.getElementById("ef1").innerHTML = data;
  else if (!data.length)
    document.getElementById("ef1").innerHTML = 'Default_Text';
}
<form action="#">
<fieldset>
<legend id="ef1">Default_Text</legend>
<input type="text" id="inputdatahere" onkeypress="echoinputdatahere()">
</fieldset>
</form>

答案 2 :(得分:-1)

&#13;
&#13;
function echoinputdatahere(elem){
    var size = elem.value.length;
    if(size == 0){
        document.getElementById("ef1").innerHTML = "Default_Text";
    }
    if(size > 0){
        document.getElementById("ef1").innerText = 
    document.getElementById("inputdatahere").value;
    }
&#13;
&#13;
&#13;

以上代码是否有效?你有一个var size value.length == 0?您的代码是否存在语法错误?