既然你問了一個解釋,而不僅僅是答案,這裏是你的解釋:
正如我在我的評論中所說的,你的代碼存在多個問題,我會在註釋的鄰近或者下面解決每個問題,指出什麼是錯的,以及爲什麼。
function calculateShipping() } // This is not an opening bracket.
// All functions(by my understanding of js) need an opening curly bracket({)
// in order to begin their declaration. You also need a closing curly bracket
// (}) to end it.
var price = parseFloat(document.getElementById('price').value);
This will add $1.50 to any purchases that are less than or equal
// On top of the fact that the 'this' keyword is reserved, the browser is
// going to treat this as multiple undefined variables, objects, etc,
// and unless this line is commented out, as this explanation is, your code
// will not work.
to $25.00.
//^same thing here; 'to' is undefined, as is $25, which is likely going to be
// treated as an variable holding an object. This is because the dot(.)
// is used to access either properties(variables) or methods(functions) of an
// object.
if (price <= 25){
price = (price) + 1.5;
} else {
//return price * 10/100
var percentToAdd=(price) * .1;
price=(price)+(percentToAdd);
}
document.getElementById('result').innerHTML='Total Order Cost:
'+price;
// Javascript does not do multi-lines like php; you either have to escape
// them or, you have to quote them. I will give examples of this below.
// And here.. here you do nothing. As noted above, you need a closing
// curly bracket to end your function declaration.
現在爲了正確的方式來編碼這個功能;
function calculateShipping() { // opening curly brackte
var price = parseFloat(document.getElementById('price').value);
/* This will add $1.50 to any purchases that are less than or equal
to $25.00.
*/
//^a multi-line comment.
if (price <= 25){
price = (price) + 1.5;
// This is really fine, except you don't really need() around 'price'.
} else {
//return price * 10/100
var percentToAdd=(price) * .1;
price=(price)+(percentToAdd);
// Same thing as above regarding parenthesis.
}
document.getElementById('result').innerHTML='Total Order Cost: \
'+price; // Escape the line^
} // Finally, end the function declaration.
如前所述,有多種方式來計算額外的行;這裏是一個:
var some_var = 'this is a string ' +
'this is another string';
鑑於上述情況,中some_var
內容將是:
這是一個字符串,這是另一個字符串
如果你想你的代碼上單獨的行,這是另一回事。你需要的HTML ..專門; break標籤:
var some_var = 'this is a string<br />this is a string on another line';
最後但並非最不重要的是,你的if/else可以簡化爲三元運算符;三元運算符是(通常)if/else子句的一行方法。下面是一個例子:
var some_var = (1 < 2) ? 'true' : 'false';
// boolean is true is false
在上文中,1小於2,並且因此,some_var
將被設置爲串「真」。否則,它將被設置爲'false'。因此,您上面的if/else可以簡化爲:
price = (price <= 25)?(price+1.5):(price+(price* .1));
除非您每行都轉義,否則Javascript不會「執行」多行。最重要的是,你永遠不會使用正確的括號來打開你的功能,也不會關閉它。您的瀏覽器有一個JavaScript控制檯的原因。在幾乎任何現代瀏覽器中都可以打F12。 – Daedalus
我不知道我明白你在說什麼?當我使用HTML時,我確實有這個工作。 – user3199950
我拒絕相信你;你的代碼語法不正確。 – Daedalus