我正在锚标签的前面添加一个图标,但是,我想阻止它添加图标多次

I'm adding a icon to the front of anchor tags however, I want to stop it from adding the icon multple times

本文关键字:添加 图标 但是 一个 标签 前面      更新时间:2023-09-26

我想限制每个锚标记多次添加图标。

如果您多次单击任何链接(foo,bar,baz),它只会继续添加很多次。

任何想法如何阻止这种情况?

$('a').click(function() {
  $('<a href="#"><i class="glyphicon glyphicon-info-sign" style="color: #ccc;"></i></a>').insertBefore($(this))
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a>foo</a>
<br>
<a>bar</a>
<br>
<a>baz</a>

你可以简单地使用 jQuery one() 方法。这样,每个click事件的每个元素最多执行一次代码。

法典:

$('a').one('click', function() {
  $('<a href="#"><i class="glyphicon glyphicon-info-sign" style="color: #ccc;"></i></a>').insertBefore($(this))
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a>foo</a>
<br>
<a>bar</a>
<br>
<a>baz</a>

当您添加图标时,将类也添加到该锚点,稍后检查它是否已经具有该类。 小提琴

$('a').click(function() {
if(!$(this).hasClass('have-icon')) {
$(this).addClass('have-icon')
  $('<a href="#"><i class="glyphicon glyphicon-info-sign" style="color: #ccc;"></i></a>').insertBefore($(this))
}
});

尝试这样做,单击按钮删除字形图标,并在删除旧字形后添加字形图标,,,我认为这会对您有所帮助....

$(document).ready(function(){
$('a').click(function() {
   var aa=$(this).prev('a:has(>i)').remove()
  // console.log(aa)
  $('<a href="#"><i class="glyphicon glyphicon-info-sign" style="color: #ccc;"></i></a>').insertBefore($(this))
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a>foo</a>
<br>
<a>bar</a>
<br>
<a>baz</a>

将 CSS 类添加到之前已添加项目的元素中。

$('a').click(function() {
  if ($(this).hasClass('item-already-added') == false)
  {
      $('<a href="#">...').insertBefore($(this));
      $(this).addClass('item-already-added');
  }
});