简体   繁体   English

如何更改JavaScript中的值?

[英]How can i change a value in javascript?

I have the folowing code: 我有以下代码:

var price1 = (length1 * width1) * priceSM / 10000;
if (price1 < 10) {
    alert("Size too small");
    return;
}
document.getElementById('result1').innerHTML = Math.round(price1);

What I need to do: 我需要做什么:

If price 1 < 10 alert AND then price1 = 10, but if price1 = 0, or bigger than 10, that's fine. 如果价格1 <10警报并且价格1 = 10,但如果价格1 = 0或大于10,则可以。

length1 and width1 are INPUTS length1width1是输入

Please help, I'm at very beginning with javascript. 请帮助,我刚开始使用javascript。

I don't know if I understand well what you want. 我不知道我想要什么。 Try this ? 尝试这个 ?

var price1=(length1*width1)*priceSM/10000;
if(price1 < 10 && price1 != 0){
    alert("Size too small");
    price1 = 10;
    return;
}
document.getElementById('result1').innerHTML=Math.round(price1);

If you want to update your element "result1" with price1 when < 10 then just remove "return;" 如果要在<10时用price1更新元素“ result1”,则只需删除“ return;”。

If it isn't what you want, please tell us and post all function's code please. 如果不是您想要的,请告诉我们并张贴所有函数的代码。

To avoid the alert when the price is zero, add that in the condition with the && operator: 为避免价格为零时发出警报,请在&&运算符的条件下添加该警报:

price1 > 0 && price1 < 10

To set the price to 10 in that case, add this to the if block: 要将价格设置为10,请将其添加到if块中:

price1 = 10

To really show the modified price (10), you should remove the return statement from that if block. 要真正显示修改后的价格(10),您应该从if块中删除return语句。 That way the code will continue to execute the last statement. 这样,代码将继续执行最后一条语句。

Finally, not really a problem, but it is better to use the textContent property instead of the innerHTML property when you intend to assign something that is plain text and not HTML. 最后,这并不是真正的问题,但是,当您打算分配纯文本而不是HTML的内容时,最好使用textContent属性而不是innerHTML属性。

So your code then becomes: 因此,您的代码将变为:

var price1 = (length1 * width1) * priceSM / 10000;
if (price1 > 0 && price1 < 10) {
    price1 = 10
    alert("Size too small");
}
document.getElementById('result1').textContent = Math.round(price1);

使用.value属性,您可以设置值。

document.getElementById("myText").value = "Hello World...";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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