简体   繁体   中英

function stopped working after adding more functions

I created a function that seems to work until I start adding more functions to the .js document.

This is the html..

<input id="nameSearch" type="text"/>
<input type="button" value="Search" onclick="search();"/>

This is the js..

 function search(){
        var bName = document.getElementById("nameSearch").value;
        alert(bName);
    };

This works until I add a new function to the external .js document. I'm not using any of these functions in the html file yet, so I'm not sure why they would affect it.

function business(b_name,add_1,add_2,city,state,zip,phone){
    this.b_name = b_name,
    this.add_1 = add_1,
    this.add_2 = add_2,
    this.city = city,
    this.state = state,
    this.zip = zip,
    this.phone = phone,
};

var ADW = new business("xxx", "xxx", "xxx", "Tucson", "AZ", "xxx", "xxx-xxx-xxxx");

var PC = new business("xxx", "xxx", "xxx", "Tucson", "AZ", "xxx", "xxx-xxx-xxxx");

var contacts = [ADW, PC];

It's because you have errors in your business function.

I believe you're looking for semi-colons instead of commas:

function business(b_name,add_1,add_2,city,state,zip,phone){
    this.b_name = b_name;
    this.add_1 = add_1;
    this.add_2 = add_2;
    this.city = city;
    this.state = state;
    this.zip = zip;
    this.phone = phone;
};

From a high level, it looks like you're trying to define an object and using the business function as an initialization method. You might want to do that instead:

let business = {
    b_name: b_name,
    add_1: add_1,
    add_2: add_2,
    city: city,
    state: state,
    zip: zip,
    phone: phone
};

Here's some further reading on the topic.

Hope this helps

If you look in your console, you will see this error:

SyntaxError: expected expression, got '}'

It even tells you which line is the problem!

Your issue is that you haven't terminated lines within the function with a semi-colon, you've used commas.

Here's the fix, which runs properly:

function business(b_name,add_1,add_2,city,state,zip,phone){
    this.b_name = b_name;
    this.add_1 = add_1;
    this.add_2 = add_2;
    this.city = city;
    this.state = state;
    this.zip = zip;
    this.phone = phone;
}

var ADW = new business("xxx", "xxx", "xxx", "Tucson", "AZ", "xxx", "xxx-xxx-xxxx");

var PC = new business("xxx", "xxx", "xxx", "Tucson", "AZ", "xxx", "xxx-xxx-xxxx");

var contacts = [ADW, PC];

And here's a Fiddle where you can see it runs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM