2016-10-01 96 views
-2

我之前發佈了一個關於我正在學習的學校問題的問題。我有我認爲是每個任務的正確功能,但我被卡住了。我需要在我的代碼中使用alert()來顯示它正在搜索的子字符串的索引位置。其他一切正常,但我不知道如何將這些信息發回到我可以打印到屏幕上的變量。我的代碼如下:如何在JavaScript中打印搜索()方法的結果?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Lesson 6 Application Project A</title> 

<script language="JavaScript" type=text/javascript> 
<!-- 
    /***************************************************************************** 
    The placeholders sub and string are used to pass as arguments the 
    user's entry into the text box and the textarea. The variable where 
    is assigned the result of a method which returns the index (integer) 
    of the first occurence of sub (the string the program is searching for). 
    Start the search at the beginning of string (the text that is being searched). 
    Since the string is zero based, add 1 is to get the correct position of sub. 
    *****************************************************************************/ 

    function search(sub, string) { 
     var where; 

     if (string.search(sub) != -1){ 
      where = alert("Your index position is: " + where); 
     } 
     else{ 
      where = alert("Could not find your string!"); 
     } 




    } 
//--> 
</script> 
</head> 

<body> 

<h3>CIW JavaScript Specialist</h3> 
<hr /> 

<form name="myForm"> 
<p> 
<strong>Look for:</strong> 
<input type="text" name="what" size="20" /> 
</p> 

<p> 
<strong>in this string:</strong> 
<textarea name="toSearch" rows="4" cols="30" wrap="virtual"> 
</textarea> 
</p> 

<p> 
<input type="button" value="Search" 
onclick="search(myForm.what.value, myForm.toSearch.value);" /> 
</p> 
</form> 

</body> 
</html> 
+1

當你在'alert'中使用它時,'alert'什麼也不返回,'where'是未定義的。 – Li357

回答

1

試試這個

function search(sub, string) { 
    var where = string.indexOf(sub); 

    if (where != -1){ 
     alert("Your index position is: " + where); 
    } 
    else{ 
     alert("Could not find your string!"); 
    } 

} 
0

你在那裏變量應assinged到搜索的結果。

function search(sub, string) { 
     var where = string.search(sub); 

     if (where != -1){ 
      alert("Your index position is: " + (where + 1)); 
     } 
     else{ 
      alert("Could not find your string!"); 
     } 
} 
-1

我對自己問題的解決方案是創建一個名爲position的變量並將其設置爲接收子字符串的索引位置。然後我可以將它添加到我的alert()中並將結果顯示在屏幕上。更正後的代碼如下:

function search(sub, string) { 
     var where; 
     var position = string.search(sub); 

     if (string.search(sub) != -1){ 
      where = alert("Your index position is: " + position); 
     } 
     else{ 
      where = alert("Could not find your string!"); 
     } 




    } 
+0

「哪裏」有什麼意義?爲什麼不'if(position!= -1)'? – 4castle

+0

我經常遇到比我需要做更多工作的問題。我看到了我出錯的地方,並且把它記錄下來。感謝所有快速回復。 – KenDubzify

相關問題