Javascript indexOf

时间:2011-10-19 13:11:14

标签: javascript

我不熟悉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>

7 个答案:

答案 0 :(得分:10)

您似乎正在尝试获取输入FirstNamegetElementById()仅返回节点本身。而是访问其值:

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

答案 1 :(得分: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);

答案 2 :(得分:1)

我想你正在尝试这个。

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

document.getElementByID应为document.getElementById

答案 5 :(得分:0)

<ul class="list-rendering"> <li v-for="item in items" v-bind:key="item"> <v-card style="padding: 10px;"> <div class="img-cont"> <v-img :src="require('@/assets/section/about.jpg')"></v-img> </div> <div class="text-cont"> <br> <base-subheading>{{ item.name }}</base-subheading> <h5>{{ item.price }}</h5> </div> </v-card> </li> </ul> export default { data () { return { items: [ { img: "@/assets/section/about.jpg", name: "Cuppy Cake", price: "$20.00" }, { img: "@/assets/section/social.jpg", name: "Red Velvet Cake", price: "$4.99" }, { img: "@/assets/section/testimonials.jpg", name: "Carrot Cake", price: "$3.00" } ] } } 方法返回字符串中第一次出现指定值的位置。 如果要搜索的值从不出现,则此方法返回indexOf()。 注意:-1方法区分大小写。

答案 6 :(得分:-1)

尝试:

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

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