2 回答

TA貢獻1111條經驗 獲得超0個贊
在你的例子中,我有一個像這樣的帶有 jQuery 的簡單 Keyup
$('#value').keyup(function (){
$('#copy-value').val($(this).val());
});
例如這個片段:
$('#value').keyup(function (){
$('#copy-value').val($(this).val());
});
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
<label for="">Input</label>
<input id="value" type="text" name="">
<br>
<label for="">Result(x2):</label>
<input id="copy-value" type="text" name="" readonly>
</div>
</body>

TA貢獻1783條經驗 獲得超4個贊
script
您實際上在文檔中的哪里有?它應該位于 CLOSINGbody
標記之前,這樣當到達它時,所有 HTML 都將被解析。如果在script
解析 HTML 之前運行,您的document.getElementById()
語句將找不到匹配的元素。
此外,thevalue
始終input
是一個字符串。您必須將其轉換為數字才能使用它進行數學運算。有多種方法可以做到這一點,您需要為輸入錯誤地包含非數字值的情況做好準備,但在下面,我通過在其前面添加 a 來轉換value
它+
。
還有一些其他的事情......
您沒有label
正確使用該元素。該for
屬性的值必須與id
標簽為“for”的表單元素的屬性值相匹配,或者您可以將表單元素嵌套在 中,label
以便它知道它與哪個元素相關。
不要使用內聯 JavaScript - 將其分離到 JavaScript 代碼中。
<body>
<div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
<label>Input
<input type="text">
</label>
<br>
<!-- Not always best to use an input for output. -->
<span>Result(x2):
<span id="out2x"></span>
</span>
</div>
<!-- Place your script just before the closing body tag
so that by the time it's reached, all the HTML elements
will have been parsed. -->
<script>
// Do your event handling in JavaScript, not with inline JavaScript
document.querySelector("input").addEventListener("keyup", function(event){
// You must convert the input string to a number
document.getElementById('out2x').textContent = 2* +this.value;
});
</script>
</body>
添加回答
舉報