我正在学习JavaScript。我当前的代码似乎可以达到总值(value),但我无法让我的部门代码来显示每人花费多少。

这行似乎是问题所在:
document.getElementById(“costeach”)。innerHTML ='£'+ price_each;

它返回NaN,但控制台中没有错误。

var a = document.getElementById("quantity");
var price = a.options[a.selectedIndex].value;
var b = document.getElementById("method");
var type = b.options[b.selectedIndex].value;

if (type == 'credit') {
var price = price * 1.034;
}

var price_each = (price / a);

document.getElementById("cost").innerHTML = '£' + price;
document.getElementById("costeach").innerHTML = '£' + price_each;
.container {
  display: inline-block;
  position: relative;
  width: 200px;
}

.image {
  display: block;
  width: 100%;
  height: auto;
  opacity: 0.6;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: .5s ease;
}

.container .overlay {
  opacity: 1;
}

button {
  padding: 10px 15px;
  cursor: pointer;
}

.text {
  color: black;
  font-family: arial;
  font-size: 50px;
  font-weight: bold;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  text-align: center;
}

span {
  display: block;
  font-size: 12px;
}
<h4>
Booking Form
</h4>
<select id="quantity" name=''>
  <option title='Option 2' value='240'>2 people</option>
  <option title='Option 3' value='330'>3 people</option>
  <option title='Option 4' value='400'>4 people</option>
  <option title='Option 3' value='500'>5 people</option>
  <option title='Option 4' value='600'>6 people</option>
</select>
<br /> Paypal Funding Method
<br />
<select id="method" name=''>
  <option title='Option 1' value='bank'>Bank Transfer</option>
  <option title='Option 2' value='debit'>Debit Card</option>
  <option title='Option 3' value='credit'>Credit card (+3.4%)</option>
</select>
<br />
<textarea placeholder="Guest names"></textarea>
<br />
<h4>
<b>Total Price</b>
<span id="cost">Hello World!</span>
<b>Price Each</b>
<span id="costeach">Hello World!</span>
</h4>
<button>
  Book
</button>

最佳答案

正如在其他答案中正确指出的那样,该错误的原因是您试图将一个数字除以DOM元素。

如果我正确理解了意图,则您正在尝试将价格除以人数。为了实现这一点,您需要指定某处的人数。当然,您可以从option的文本中提取此数字或从其索引中获取该数字,但是更干净的方法是在 data属性中定义此数据,例如

<option title='Option 2' value='240' data-num-persons='2'>2 people</option>
<option title='Option 3' value='330' data-num-persons='3'>3 people</option>
<option title='Option 4' value='400' data-num-persons='4'>4 people</option>

然后,您可以提取人数并进行如下划分:
var number_of_people = a.options[a.selectedIndex].getAttribute('data-num-persons');
var price_each = (price / number_of_people);

您的其余代码保持不变。
See fiddle.

使用这种方法,您无需使选项的文本或标题都可以机读,实际数据(人数)将与表示无关。例如。如果将文本更改为“一个人”,“两个人”等,该代码仍然可以使用。

10-06 07:38
查看更多