如果元素存在,如何使用 .after() 作为 .html()
How to use .after() as .html() if element exists?
这是我的代码:
$('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>
相关文章:
- 选择<脚本></脚本>作为html正文中的纯文本
- 将信息框作为HTML标签属性(AngularJS)添加到Google Maps Marker
- 从自身获取对脚本作为 HTML DOM 元素的引用
- 如果元素存在,如何使用 .after() 作为 .html()
- 将 JSON 作为 HTML 中的资源加载以避免引导 ajax
- 如何使用 angular2 检索到的数据作为 html 标记
- 使用网络摄像头作为 HTML 背景
- 如何在数组的元素之间插入空格,该数组作为 HTML 表单的输入读取
- 是否可以使用主干模型的 cid 作为 html id 属性?它是否保证是独一无二的
- 将表作为 html 形式的隐藏值传递 - 奇怪的单/双引号问题
- 使用“内容”属性作为 HTML 模板
- 在javascript中使用斜杠作为html模板
- 如何在 JavaScript 函数中使用 JavaScript 变量作为 HTML 输入名称
- 如何编写javascript变量作为html中img标记的源代码
- 通过ajax和外接程序表将表行作为HTML代码返回
- CSS和JS在用gulp和angular.JS构建的网站中作为HTML的副本加载
- 使用变量作为HTML元素属性
- Fancybox-是否可以使用javascript变量字符串作为HTML内容
- 如何处理以.txt结尾的url到iframe作为html
- 图像作为html按钮