2016-12-27 33 views
-3

你能告訴我爲什麼控制檯說,這是不是一個功能?使用Javascript - 讓我的字符串的第一個字符 - 錯誤

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

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

然後我通過這個獲得text:

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

所以控制檯說: 「遺漏的類型錯誤:firstAuthorName.slice是不是一個函數」

+1

'firstAuthorName'是HTML元素,而不是一個字符串。根據是什麼,你還是需要諮詢正確的屬性來訪問它的字符串的內容(如'e.value'或'e.textContent'等) –

+1

你忘了'.value','.innerHTML'或'。'.slice'之前的innerText'。 'document.getElementById(「firstAuthorName」)'不是一個字符串。 – Xufox

+0

嗯,我得到了作者姓名的輸入,我只需要把他的名字的第一個字符 – lookasz

回答

1

您需要訪問的內容的HTML元素,並獲得第一個字符。您正嘗試從HTML DOM對象本身獲取第一個字母,而不是該對象的內容。

There are 3 standard ways to extract content of an element and which you use depends on the kind of element you have and the kind of content it contains:

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內容。當有問題的元素包含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>

相關問題