簡體   English   中英

如何在 JavaScript 中打印 search() 方法的結果?

[英]How do I print the result of a search() method in JavaScript?

我之前發布了一個關於我正在研究的學校問題的問題。 我認為每個任務都有正確的功能,但我被卡住了。 我需要讓代碼中的 alert() 顯示它正在搜索的子字符串的索引位置。 其他一切都有效,但我不知道如何將該信息發送回可以打印到屏幕上的變量。 我的代碼如下:

<!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>

嘗試這個

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

}

您的 where 變量應該分配給搜索結果。

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

我對自己問題的解決方案是創建一個名為 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!");
        } 




    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM