简体   繁体   English

jQuery:自动附加或替换?

[英]jQuery : append or replace automatic?

################## SIMPLIFIED VERSION  ##################

What I need:我需要的:

$('body').appendOrReplace('<div id="foo"></div>')

The first time, the result is :第一次,结果是:

<body><div id="foo"></div></body>

Now, if I re-run the same code, the result should not change!现在,如果我重新运行相同的代码,结果应该不会改变!

If there is any child in the DOM to append like $('body').appendOrReplace('<div id="foo"><p id="bar"></p></div>') , appendOrReplace must just take the id of first element.如果 DOM 中有$('body').appendOrReplace('<div id="foo"><p id="bar"></p></div>')要追加,如$('body').appendOrReplace('<div id="foo"><p id="bar"></p></div>') , appendOrReplace 必须只需取第一个元素的 id。

The problem is : the argument is a string (not a dom), so I can't get easily the id, to test if already exist.问题是:参数是一个字符串(不是一个 dom),所以我不能很容易地得到 id,来测试是否已经存在。

################## MY USE CASE (EDIT)  ##################

I use template JST (with Rails), so I have this code :我使用模板 JST(带 Rails),所以我有这个代码:

$('#page').append(app.JST('path/to/template'));

JST template can return a full page of html (a very long string of future HTML). JST 模板可以返回一整页的 html(未来 HTML 的一个很长的字符串)。

I need to ensure unicity of template.我需要确保模板的唯一性。 Each template begin by an element with an unique ID.每个模板都以具有唯一 ID 的元素开头。

So I need a method jquery to append this full DOM if and only if the element not exist, or replace if already exist.所以我需要一个方法 jquery 当且仅当元素不存在时附加这个完整的 DOM,或者如果已经存在则替换。

You just need like this: 你只需要这样:

if ($("#foo").length == 1)
  // Replace
else
  // Append

You can create a function like this: 你可以创建一个这样的函数:

$.fn.appendOrReplace = function (param) {
  // do that
}

And the next thing you can do is: 接下来你可以做的是:

if ($("#foo").length == 1)
  $('body').replace('<div id="foo"></div>');
else
  $('body').append('<div id="foo"></div>');

The snippet from the other answer did not work for me.另一个答案的片段对我不起作用。

This one is working:这个正在工作:

if ($("#foo").length > 0)
  $('#foo').replaceWith('<div id="foo">updated</div>');
else
  $('body').append('<div id="foo">initial</div>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM