在输入旁边动态添加元素

Dynamically add element beside inputs

假设我有 10 个不同的输入字段,每个字段都有一个 ID。

<input id="blue">
<input id="pink">
<input id="red">
<!-- ... -->

在这些输入字段旁边,我想创建一个 <a> 元素,其 href 属性应动态包含其旁边按钮的 ID:

<input id="blue">
<a href="mylink.com/blue"><a/>

<input id="pink">
<a href="mylink.com/pink"><a/>

<input id="red">
<a href="mylink.com/red"><a/>

这是我正在使用的简单代码:

$('input').prepend('<a href="mylink.com/'+ID of the element next to this a tag+'/'</a>');

$.fn.preprend 您尝试使用的方法不是解决此问题的正确工具,因为它将内容 插入 元素,而您想将其附加到旁边它作为兄弟姐妹。

当您需要以类似的方式对一组元素进行操作时,您应该考虑为它们赋予相同的 class 名称,以便于 DOM 查询。那么在$.fn.after方法的帮助下就很容易了:

// $('input') will also work of course
$('.input').after(function () {
  return $('<a>', {
    href: 'http://mylink.com/' + this.id,
    text: this.id
  })
  // or return string:
  // return '<a href="http://mylink.com/' + this.id + '">' + this.id + '</a>'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="blue" class="input">
<input id="pink" class="input">
<input id="red" class="input">

纯js方法

https://jsfiddle.net/r5thro2w/

<input id="blue">
<input id="pink">
<input id="red">

window.onload = addAnchors();

function addAnchors() {
   let allInputs = document.getElementsByTagName("input");   
   for(i=0;i<allInputs.length;i++) {    
    let anchorTag = document.createElement('a');
    anchorTag.setAttribute('href',allInputs[i].getAttribute("id"));
    anchorTag.innerHTML = allInputs[i].getAttribute("id");
    allInputs[i].insertAdjacentElement("afterend", anchorTag);
   }   
}

这样试试

https://jsfiddle.net/o2gxgz9r/18686/

<div class="myHref">
 <input class="clickMe" id="blue">
 <a class="link" href="hello.com"></a>
   </div>
     <div class="myHref">
<input class="clickMe" id="pink">
<a class="link" href="hello.com"></a>
</div>
    <div class="myHref">
  <input class="clickMe" id="red">
      <a class="link" href="hello.com"></a>
 </div>

$(document).ready(function() {
    $('.clickMe').change(function(e){
       var textInput    =   $(this).val();
   $ele = $(this).closest('.myHref').find('.link');
     var _href =$(this).closest('.myHref').find('.link').attr("href");

     $(this).closest('.myHref').find('.link').attr("href", _href +'#'+textInput);

 var _href2 =$(this).closest('.myHref').find('.link').attr("href");
alert(_href2);
 });
 });