【问题标题】:Javascript - Getting the first character of my string - errorJavascript - 获取我的字符串的第一个字符 - 错误
【发布时间】:2016-12-28 11:01:32
【问题描述】:

你能告诉我为什么控制台说它不是一个函数吗?

  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 is not a function”

【问题讨论】:

  • firstAuthorName 是一个 HTMLElement,而不是一个字符串。根据它是什么,您仍然需要查阅正确的属性来访问其字符串内容(如e.valuee.textContent 等)
  • 您在.slice 之前忘记了.value.innerHTML.innerTextdocument.getElementById("firstAuthorName") 不是字符串。
  • 嗯,我得到了作者姓名的输入,我只需要他名字的第一个字符

标签: javascript jquery html


【解决方案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">

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

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

以下是正确使用上述所有 3 个的示例:

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);

  });

});
<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>

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

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));
});
<input id="firstAuthorName" type="text" placeholder="type in me and then click the button">
<button>Click Me</button>

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 2011-03-26
    • 2012-11-10
    • 2015-05-21
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多