【发布时间】:2021-04-25 16:23:35
【问题描述】:
详情
我有一个例子,输入和输出元素在同一个站点上。
- 生成
<output>元素值 -
<input>元素值由用户指定 - 还有另一个
<output>元素,其中显示了 1. 和 2. 元素产品。
示例应该是事件驱动的。
- 如果用户输入一个输入,产品必须改变。
- 如果用户生成了新编号,则产品也必须更改。
问题:
- 只有 Typed 参数会导致 Product 元素的值发生变化。可能有一些原因,由于 Generated number 的变化没有触发产品计算。
问题:
如果更改 Generated number 或 Typed 参数,我如何修改我的示例以计算 Product?
示例
function generate() {
var generatedValue = Math.floor(Math.random() * 100);
$("#myinput1").val(generatedValue);
$("#myinput1").trigger("myOwnEvent");
};
$('#myinput2')[0].addEventListener('input', calculateTheProduct);
$('#myinput3')[0].addEventListener('myOwnEvent', calculateTheProduct);
function calculateTheProduct() {
var inputGeneratedValue = $('#myinput1')[0].value;
var inputTypedParameter = $('#myinput2')[0].value;
var product = inputGeneratedValue * inputTypedParameter;
$('#myinput3').val(product);
};
body {
margin: 20px;
font-size: 30px;
}
label {
font-size: 20px;
margin: 20px;
font-weight: bold;
}
.inputClass {
font-size: 20px;
max-width: 200px;
margin: 20px 0 20px 0;
background-color: #DFDFDF;
}
.typeInput {
background-color: white;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<h1>Hello World</h1>
<button onclick="generate()">Generate</button>
<div class="input-group" class="numberDiv">
<label for="myinput1">Generated number:</label>
<output id="myinput1" class="form-control inputClass">
0
</output>
</div>
<div class="input-group" class="numberDiv">
<label for="myinput1">Typed parameter:</label>
<input id="myinput2" class="form-control inputClass typeInput" value="0">
</div>
<div class="input-group" class="numberDiv">
<label for="myinput3">Product:</label>
<output id="myinput3" class="form-control inputClass" value="0">
0
</output>
</div>
【问题讨论】:
-
嗨,为什么不简单地在
generate()函数中调用calculateTheProduct()函数呢? -
@Swati 这可以解决我在描述的示例中展示的问题,但我需要为此任务找到基于事件/事件控制的解决方案。我的主要问题是我提到的:如何在这个简短的示例中正确启动 HTML 元素的事件触发?
标签: javascript html jquery dom-events jquery-events