【问题标题】:Add text to an input and then append to a text box with text already in it?将文本添加到输入,然后附加到已包含文本的文本框?
【发布时间】:2022-01-21 07:57:38
【问题描述】:

我正在尝试制作一个 JavaScript/jQuery 脚本,该脚本将文本从输入添加到 锚标记,其中已经包含文本。这是我要完成的一个示例:

<!-- BEFORE INPUT HAS BEEN PRESSED -->
<a> Add an attachment for https://thislink/ </a>
<br>
<!-- AFTER INPUT AS BEEN USED AND SUBMIT WAS PRESSED -->
<a href="https://thislink/[text-from-input]"> [text-from-input] </a>
<form>
   <input> text from this will be added to the text area </input>
   <input type="submit" value="Submit"></input>
</form>

【问题讨论】:

  • 那么到目前为止,您尝试了什么?你面临什么问题?
  • 这不是问题,我在问怎么做。
  • 首先给你的锚标签添加一个id。然后在 JS 中使用 document.getElementById 获取该元素并修改其 href 属性和 innerHTML。

标签: javascript jquery


【解决方案1】:

给你的ainput 一个ID。 使用javascript获取输入值。然后使用innerHTML 将输入值附加到a 文本中。

function appendText(e){
      e.preventDefault();
       var inputValue = document.getElementById('input').value
        document.getElementById('theLink').innerHTML += inputValue
}
 <a id="theLink" href="https://thislink/[text-from-input]"> [text-from-input] </a>
<form>
     <input id="input"> text from this will be added to the text area </input>
     <input onclick="appendText(event)" type="submit" value="Submit"/>
 </form>


     

【讨论】:

    【解决方案2】:

    您可以从 DOM 中选择所需的元素,然后在提交表单时添加一个监听器,并在事件处理程序中简单地获取输入的内容并更新 DOM。

    以下示例将帮助您入门。 此外,在使用之前清理用户输入总是一个好主意。

    const link = document.querySelector(".link");
    const form = document.querySelector(".form");
    
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      const userInput = e.target.elements["attachment-input"].value;
      link.href = `https://thislink/${userInput}`;
      link.textContent = userInput;
    });
    <a class="link">Add an attachment for https://thislink/</a>
    <br>
    <form class="form">
       <label for="attachment-input">Enter Attachment</label>
       <input type="text" id="attachment-input">
       <input type="submit" value="Submit">
    </form>

    【讨论】:

      【解决方案3】:

      您可以利用id 属性让容器保存您的锚标记,然后使用用户写入的任何值动态更新其锚标记:

      function changeLink() {
        document.getElementById("dynamic-link").innerHTML = `<a href='https://thislink/${document.getElementById("user-input").value}'>Link Generated</a>`
      }
      <div> Add an attachment for https://thislink/ </div>
      <br>
      <div id="dynamic-link">
      </div>
      <br/>
      <form>
        <input type="text" id="user-input" />
        <br/><br/>
        <button type="button" onclick="changeLink()">Submit</button>
      </form>

      【讨论】:

        猜你喜欢
        • 2020-03-12
        • 1970-01-01
        • 2013-12-26
        • 1970-01-01
        • 2017-03-25
        • 2020-12-07
        • 2013-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多