Javascript indexOf

6

我对JavaScript不是很了解,所以我在尝试让以下脚本工作时遇到了问题。 我需要检查输入的姓名是否也包含在消息中。

<input type="hidden" id="Message" value="<%= rsDetail.Fields("Message") %>">
<input type="hidden" id="FirstName" value="<%= rsDetail.Fields("FirstName")%>">

<script type="text/javascript">
<!--
function NameCheck(){
var FirstName=document.getElementByID('FirstName');
var CardMessage=document.getElementByID('Message');
var aPosition = CardMessage.indexOf('FirstName');

if (aPosition == -1)
alert("Name Not In Message.");
}
-->
</script>

<a href="NextPage.asp" onClick="NameCheck();">Proceed</a>

document.getElementById() 返回的是元素,而不是元素的值。要获取元素的值,可以使用 document.getElementById('someId').value - aroth
7个回答

12

看起来你想获取输入框 FirstName。但是 getElementById() 只会返回节点本身,你需要访问它的值:

var FirstName = document.getElementById('FirstName').value;
var CardMessage = document.getElementById('Message').value;

// Then use the variable `FirstName` instead of the quoted string
var aPosition = CardMessage.indexOf(FirstName);

// Best practice would be to use === for strict type comarison here...
if (aPosition === -1)
  alert("Name Not In Message.");
}

另外,请注意,您拼错了 getElementById,末尾应该是小写字母 d,而不是大写字母。


我该如何修改代码,以便在警告框中获得“是”和“否”选项,其中“是”允许用户继续进行,而“否”则保留他们在页面上。 - Darren Cook
1
@Darren Cook,使用confirm()代替alert()并返回其值:return confirm('消息中没有名称'); - Michael Berkowski

1

'FirstName' 用引号括起来表示它是一个字符串,而不是变量 FirstName。你需要:

// remove the quote, pass the variable FirstName instead of string 'FirstName'
var aPosition = CardMessage.indexOf(FirstName);

编辑:我之前漏掉了两个东西。第一,您需要获取节点的值,第二是大写字母 D。所以正确的代码是:

var FirstName = document.getElementById('FirstName').value;
var aPosition = CardMessage.indexOf(FirstName);

1

我想这就是你所尝试的。

var FirstName=document.getElementById('FirstName').value;
var CardMessage=document.getElementById('Message').value;
var aPosition = CardMessage.indexOf( FirstName );

1

使用jQuery的最佳方式。您的代码可以被压缩到最多2行:

$("#click").click(function() {
    var found = $('#Message').val().indexOf($("#FirstName").val());
    console.log(found);
});

0

document.getElementByID 应该是 document.getElementById


0

indexOf() 方法返回一个字符串中指定值的首次出现位置。

如果要搜索的值从未出现,则此方法返回-1

注意:indexOf() 方法区分大小写。


-1

尝试:

var FirstName=document.getElementByID('FirstName');
var aPosition = CardMessage.indexOf(FirstName);

在你的例子中,你正在寻找以下字符串FirstName,而不是变量FirstName的值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接