Javascript - 获取我的字符串的第一个字符 - 错误

时间:2016-12-27 18:44:41

标签: javascript jquery html

你能告诉我为什么控制台说这不是一个功能吗?

  var firstAuthorName = document.getElementById("firstAuthorName");

var firstCharacter =  console.log(firstAuthorName.slice(0,1));    

然后我得到了这个文本:

div.innerHTML += firstCharacter.value + ", " + firstAuthorInitials.value + ", " + firstAuthorSurname.value + ". ";    

所以控制台说:" Uncaught TypeError:firstAuthorName.slice不是函数"

1 个答案:

答案 0 :(得分:1)

您需要访问HTML元素的内容并获取该元素的第一个字符。您试图从HTML DOM对象本身获取第一个字母,而不是对象的内容。

  

提取元素的内容有3种标准方法   你使用取决于你拥有的元素的种类和种类   它包含的内容:

1a上。 value :如果元素是表单字段(单选按钮,复选框,     文本框等)value始终用于获取保留的值     在形式领域。

1b中。 value还用于获取HTML元素属性的值,如下所示:



var src = document.querySelector("img").attributes[0].value;
console.log("The value of the \"src\" attribute of the image is: " + src);

<img src="images/someImage.jpg">
&#13;
&#13;
&#13;

对于非表单字段元素,您可以使用textContentinnerHTML

  1. textContent 只获取作为元素内容的字符(减去任何HTML)。如果元素仅包含 人类可消费文本,这很可能是你想要的。
  2. innerHTML 获取元素的内容,包括任何HTML内容。当有问题的元素包含HTML内容时使用此选项 你想要的是HTML,而不是文本。使用innerHTML时 而不是textContent工作,它稍微贵一点 要执行的操作,因为您要求HTML解析器进行解析 内容,因此不要在非HTML内容上使用innerHTML
  3. 这里正确使用了上述所有3个样本:

    &#13;
    &#13;
    window.addEventListener("DOMContentLoaded", function(){
    
      document.querySelector("button").addEventListener("click", function(){
    
        var input = document.getElementById("txtTest");
        var parent = document.getElementById("parent");
    
        // textContent will get the text characters as they are:
        var textOnly =  console.log("textContent of parent div is: " + parent.textContent);
    
        // innerHTML will get the content of the element but will parse its HTML:
        var htmlContent =  console.log("innerHTML of parent div is: " + parent.innerHTML);
    
        // value is ONLY for form-field elements:
        console.log("The value of the div is: " + parent.value);  // undefined
        console.log("The value of the textbox is: " + input.value);
    
      });
    
    });
    &#13;
    <input id="txtTest" type="text" placeholder="type in me and then click the button">
    <div id="parent">
      <p>Nested child HTML</p>
    </div>
    
    <button>Click me to get results</button>
    &#13;
    &#13;
    &#13;

    因此,如果您的方案是内容位于文本框中,那么您的解决方案就是使用value,如下所示:

    &#13;
    &#13;
    var firstAuthorName = document.getElementById("firstAuthorName");
    var button = document.querySelector("button");
    
    button.addEventListener("click", function(){
      console.log("The first character in the textbox is: " + firstAuthorName.value.slice(0,1));
    });
    &#13;
    <input id="firstAuthorName" type="text" placeholder="type in me and then click the button">
    <button>Click Me</button>
    &#13;
    &#13;
    &#13;