2016-09-27 84 views
-2

我創建了一個函數,似乎工作,直到我開始添加更多的功能到.js文件。添加更多功能後功能停止工作

這是HTML ..

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

這是JS ..

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

這工作,直到我添加一個新功能到外部的.js文件。我沒有在html文件中使用這些函數,所以我不確定它們爲什麼會影響它。

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]; 
+0

你會得到什麼錯誤? – raphael75

+1

查看您的開發者控制檯。是否有任何錯誤? (學習使用你的瀏覽器的開發者控制檯將是*最好的事情*你可以在你想要開發javascript中做的事情) –

+1

'this.b_name = b_name,'<---這裏的逗號是什麼? – zerkms

回答

3

這是因爲你在你的business函數中有錯誤。

我相信你正在尋找分號,而不是逗號:

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; 
}; 

從一個高的水平,它看起來像你試圖定義一個對象,並使用business功能作爲一個初始化方法。你可能會想這樣做,而不是:

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.

希望這有助於

1

如果您在控制檯看,你會看到這樣的錯誤:

SyntaxError: expected expression, got '}' 

它甚至告訴你哪一行是問題!

你的問題是你沒有用分號終止函數中的行,你已經使用了逗號。

這裏的修復,其正常運行:

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]; 

而這裏的a Fiddle在這裏你可以看到它運行。