代码之家  ›  专栏  ›  技术社区  ›  DanielsV

基于JavaScript输入用文本填充HTML元素

  •  -2
  • DanielsV  · 技术社区  · 7 年前

    现在的代码只用于填充另一个输入字段。但我需要它来填充一个常规段落,而不是另一个输入字段。我该怎么做?

    $(".first").on('keydown',function(){
      $(".second").val($(this).val());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" class="first" placeholder="type here">
    <input type="text" class="second" placeholder="here it is the reuslt">
    4 回复  |  直到 7 年前
        1
  •  1
  •   Master Yoda    7 年前

    使用 text 函数将文本插入元素。

    id's classes 可用于指定 具体的 元素( id )或者 元素的数量( class ). 在下面的示例中,我添加了一个类来更改每个颜色 <p> 使用css将标签标记为红色。在我们的JS中,我们 选择 在个人id上。

    //selecting on the insertTextHere id to specify the <p> tag to insert text into
    $("#first").on('keyup', function() {
      $("#insertTextHere").text($(this).val());
    });
    
    //you can even set it up to revert back to the original text on click
    $("#resetButton").on("click", function() {
      var resetText = "Type into input to overwrite this text";
      //insert original string as text
      $("#insertTextHere").text(resetText);
      //empty the input value
      $("#first").val("");
    });
    .text {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="first" placeholder="type here">
    <button id="resetButton" type="button">reset text</button>
    <div>
      <p id="insertTextHere" class="text">Type into input to overwrite this text</p>
      <p class="text">This text will not be overwritten</p>
    </div>
        2
  •  0
  •   Scott Marcus    7 年前

    表单字段具有 value val() 方法)。常规元素具有 textContent 属性(或者在JQuery中,是一个 text() 方法)。

    此外,您应该使用 keyup 以获取键入的所有文本。

    $(".first").on('keyup',function(){
        $("#output").text($(this).val());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" class="first" placeholder="type here">
    <p id="output"></p>
        3
  •  0
  •   Roland Ruul    7 年前

    输入 '事件而不是 向下键/向上键 -if用户 粘贴 价值 他们两个都不行 . 所以用这个代替:

    $('.inputClass').on('input', function() {
        $('.paragraphClass').text($(this).val());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" class="inputClass">
    <p class="paragraphClass"></p>
        4
  •  -1
  •   Onur Öçalan    7 年前
    $(".first").on('keydown',function(){
        $('.selectorOfDOM').text($(this).val());
    }
    

    你可以在这个链接上找到类似的问题。 Fill div with text