如何使用charAt()?

时间:2019-09-23 06:02:06

标签: javascript html

我想区分用户输入的值。

用户使用输入表单添加值。

如果“#”是用户输入的值的开头。 重定向到A

除此之外 重定向到B

我试图通过使用charAt()来区分 但不起作用

我是第一次使用javascript,因此有很多错误。 你能看一下我的代码吗?

html / javascript

<form>
    <input id="pathID" placeholder="Search ..." style="height:40px; line-height:40px; padding:0 15px;"> 
    <input onclick="return findSharp()" type="submit" value="Search" style="background:#222;">
</form>

<script>
    function findSharp() {
        var stringName = document.getElementById("pathID").value;

        if (stringName.charAt(0) == '#') {
            findURLA();
        } else {
            fidneURLB();
        }
    }

    function findURLA() {
        window.location.href = 'http://localhost:8181/activity-2/' + '?' + 'hashtag/' + document.getElementById("pathID").value;

        return false;
    }

    function findURLB(){
        window.location.href = 'http://localhost:8181/mainpage/' + '?' + 'activity/' + document.getElementById("pathID").value;

        return false;
    }
</script>

4 个答案:

答案 0 :(得分:0)

您的代码为true,但是您使用的是type =“ submit”。因此,如果将其更改为button。你可以做到的。

此外,您键入了错误的函数名称。更改为findURLB

handleBackPress() {
this.props.navigation.goBack(null);
return true;
}

答案 1 :(得分:0)

我认为您需要验证您的网址

function isValidUrl(Url){
    if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(Url))
        alert("URL is Valid");
    else
        alert("URL is Invalid");
}
URL:  <input id="Url" onchange="isValidUrl(this.value)" />

答案 2 :(得分:0)

将输入类型用作对接,而不是提交

如果要重定向,直接将参数传递给函数

<form> <input id="pathID" placeholder="Search ..." style="height:40px; line-height:40px; padding:0 15px;"> 

<input onclick="return findSharp()" type="button" value="Search" style="background:#222;color:white;padding:10px"></form>

<script>
function findSharp(){
var stringName = document.getElementById("pathID").value;
if(stringName.charAt(0) == '#'){
	findURLA(stringName)
 }else{
	 findURLB(stringName)
 }
}

function findURLA(data){
window.location.href = 'http://localhost:8181/activity-2/' + '?' + 'hashtag/' + data;
return false;
}

function findURLB(data){
window.location.href = 'http://localhost:8181/mainpage/' + '?' + 'activity/' + data;
}
</script>

答案 3 :(得分:0)

您使用了错误的函数名称“ fidneURLB”。

如果您将其更正为“ findURLB”,则代码应该可以正常工作。

检查以下带有注释的代码,以突出显示错误的函数调用位置。

<script>
function findSharp(){
var stringName = document.getElementById("pathID").value;
if(stringName.charAt(0) == '#'){
 findURLA()
 }
else{
//The function name was incorrect earlier :"fidneURLB"
 findURLB()
 }
}

function findURLA(){
document.write("I AM URL A");
return false;
}

function findURLB(){
document.write("I AM URL B");
return false;
}
</script>
<form> 
    
    <input id="pathID" placeholder="Search ..." style="height:40px; line-height:40px; padding:0 15px;"> 

    <input onclick="return findSharp()" type="submit" value="Search">

</form>