如果元素存在,如何使用 .after() 作为 .html()

How to use .after() as .html() if element exists?

本文关键字:作为 html after 何使用 元素 存在 如果      更新时间:2023-09-26

这是我的代码:

$('button').on('click', function(){
    $('div').after('<p>this element should be unique</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a div</div>
<button>click</button>

如您所见,当我多次单击该<button>时,我会看到已创建的多个元素,如下所示:

<div>this is a div</div>
<p>this element should be unique</p>
<p>this element should be unique</p>
<p>this element should be unique</p>
<button>click</button>

但我想在<div>之后附加该<p>,前提是它不存在,否则我想替换它。无论如何,我想要这个输出:(一次单击和多次单击)

<div>this is a div</div>
<p>this element should be unique</p>
<button>click</button>

我该怎么做?

如果你只有一个p

编辑

$('button').on('click', function() {
  if (!($('div').next('p').length)) {
    $('div').after('<p>this element should be unique</p>');
  }else{
    $('div').next('p').html('this will replace');
  }
});

您可以检查该元素是否存在,以及它是否确实更新了内容。 这样的事情应该有效:

var index = 0;
$('button').on('click', function(){
index++;
    if($('#myWrapper').length == 0) {
        $('div').after('<p id="myWrapper">this element should be unique' + index +'</p>');
    } else {
        $('#myWrapper').html('<p>this element should be unique' + index +'</p>');
    }
});

JS小提琴示例:https://jsfiddle.net/igor_9000/44mgz316/3/

希望对您有所帮助!

不知道你是如何生成<p>元素的,在这里你可以检查一些通用的解决方案,并implement你自己的逻辑

var text;
$('#text').on('change', function() {
  text = $(this).val();
});
   $('button').on('click', function() {
  if ($('div').next('p:contains(' + text + ')').length) {
  } else {
    $('div').next('p').remove();
    $('div').after('<p>' + text + '</p>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<div>this is a div</div>
<button>click</button>

最好添加一个包装器,并替换其内容:

var $target = null;
$('button').on('click', function(){
  if(!$target) $target = $('<div></div>').insertAfter('div');
  $target.html('<p>this element should be unique</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a div</div>
<button>click</button>