繁体   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