亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用onkeyup在標簽內顯示用戶輸入值

如何使用onkeyup在標簽內顯示用戶輸入值

千萬里不及你 2023-08-10 15:21:27
我想知道如何使用 onkeyup 方法將文本框中輸入的值顯示到標簽中。我可以將其顯示在文本框中。這就是我到目前為止所做的:<script>    function multiply(value){        var x;        x= 2*value;        document.getElementById('out2x').value=x;    }</script><body>  <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">    <label for="">Input</label>    <input type="text" name="" onkeyup="multiply(this.value);">    <br>    <label for="">Result(x2):</label>    <input type="text" id="out2x" name="" readonly>  </div></body>我嘗試將 id 'out2x' 設置為標簽,但它不起作用。
查看完整描述

2 回答

?
catspeake

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>


查看完整回答
反對 回復 2023-08-10
?
慕娘9325324

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>


查看完整回答
反對 回復 2023-08-10
  • 2 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號