jQuery:如果不存在,添加dom元素 [英] jQuery: add dom element if it does not exist

查看:111
本文介绍了jQuery:如果不存在,添加dom元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长问题

是否可以只添加一个DOM元素(如果不存在)

Is it possible to add a DOM element only if it does not already exists?

示例

我已经实现了这样的要求:

I have implemented the requirement like so:

var ins = $("a[@id='iframeUrl']");
ins.siblings('#myIframe:first').remove().end().parent().prepend('<iframe id="myIframe"  src="'+ins.attr("href")+'"></iframe>');

可以用更优雅的东西来替换第二行吗?像 ins.siblings('#myIframe:first')。is()。not()。parent()。prepend ...

Is it possible to replace the second line with something more elegant? Like ins.siblings('#myIframe:first').is().not().parent().prepend ...

我可以检查 ins.siblings('#myIframe:first')。长度然后添加IFrame,但好奇的接管了,我

I could check ins.siblings('#myIframe:first').length and then add IFrame, but the curiosity took over and I'm trying to do that in the least amount of statements possible.

推荐答案

我认为你建议的方式(计数长度)是最多的有效的方式,即使它涉及更多的代码:

I think the way you suggested (counting length) is the most efficient way, even if it does involve a bit more code:

var ins = $("a[@id='iframeUrl']");

if(ins.siblings('#myIframe:first').length == 0)
    ins.parent().prepend('<iframe id="myIframe"  src="'+ins.attr("href")+'"></iframe>');

另外,:first selector将是因为这里应该只有一个元素,所以:

Also, the :first selector would be redundant here as there should only ever be one element with that ID, so:

var ins = $("a[@id='iframeUrl']");

if($('#myIframe').length == 0)
    ins.parent().prepend('<iframe id="myIframe"  src="'+ins.attr("href")+'"></iframe>');

也可以工作。

编辑:如Fydo在评论中提到的,长度检查也可以缩短,所以最简单的形式是:

as Fydo mentions in the comments, the length check can also be shortened, so the tersest form would be:

var ins = $("a[@id='iframeUrl']");

if(!$('#myIframe').length)
    ins.parent().prepend('<iframe id="myIframe"  src="'+ins.attr("href")+'"></iframe>');

请注意在if条件下选择器之前的感叹号!

Note the exclamation mark before the selector in the if condition!

这篇关于jQuery:如果不存在,添加dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆