如何添加新的<a> with jquery when the </a> <a> is clicked?</a>

时间:2015-01-23 22:49:47

标签: javascript jquery html

<div class="links">
<a href="#">#1</a>
</div>

所以当我点击锚标签时,我希望它用jquery添加一个新的锚标签。我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

我建议,鉴于问题本身缺乏信息:

// binds a click event-handler to the '.links' element,
// which executes the function *if* that click took place
// on an <a> element:
$('.links').on('click', 'a', function () {
    // creates an <a> element, setting its 'href' to '#'
    // and its text to 'a new link'
    $('<a />', {
        'href' : '#',
        'text' : 'a new link'
    // then inserts it after the clicked <a> element:
    }).insertAfter(this);
});

鉴于增加的细节:

  

我想要它以便它会乘以<a href="#">#1</a>但是使1 a 2然后2 a 3等等

以下内容应该更合适:

// binds the click event-handler to the .links element,
// executing the function if the click was initiated on
// (or within) an <a> element:
$('.links').on('click', 'a', function(e) {
  // prevents the default action of the link:
  e.preventDefault();
  // caching a reference to the parentNode of the clicked-link:
  var parent = this.parentNode;

  // creating a new <a> element, setting its:
  $('<a />', {
    // text to the character '#' + the sum of the number of
    // children + 1:
    'text' : '#' + (parent.children.length + 1),
    // setting the href to '#':
    'href' : '#'
  // appending the created-<a> to the parent element:  
  }).appendTo(parent);
});

$('.links').on('click', 'a', function(e) {
  e.preventDefault();
  var parent = this.parentNode;
  $('<a />', {
    'text' : '#' + (parent.children.length + 1),
    'href' : '#'
  }).appendTo(parent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links">
  <a href="#">#1</a>
</div>

答案 1 :(得分:0)

尝试类似:

$('.links a').bind('click', function(){
    $('.links').append('<a href="#">#2</a>');
});

答案 2 :(得分:0)

  var linkNumber = 2;

  function addLink() {
      $('.links').append('<br/><a onclick=\"addLink()\" href=\"#\">#'+ linkNumber + '</a>');
      linkNumber++
  };
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links">
  <a onclick="addLink()" href="#">#1</a>
</div>