[英]Prevent element from updating - JQuery
我选择页面的一个元素:
$mainSection = $('#main');
然后我通过AJAX将更多元素添加到<div id="main"></div>
元素中。 下次我调用$mainSection
,新添加的元素也在其中。 但是我不想要那个。 我希望变量$mainSection
仅包含页面初始呈现时的内容。 我找不到防止jQuery更新的方法。
我尝试了这个:
$(document).ready(function(){
$mainSection = $('#main').clone(true);
然后,我将新元素添加到#main中,然后检查是否通过以下方式找到了它们:
$foundElement = $($mainSection + ":not(:has(*)):not(script):contains('"+newlyAddedContent+"')");
在页面加载时,它们不存在。 但是在我添加它们之后,它们就被找到了。
我也尝试过:
$mainSection = $('#main').html();
$mainSection = $($mainSection);
也没有工作。
这是一个jsFiddle来说明我的观点:
问题出在该行中:$ foundElement = $($ mainSection +“:not(:has(*)):not(script):contains('” + newlyAddedContent +“')”);
当我这样做时,总会以某种方式始终搜索整个文档。
您可以使用.clone(true)
:
$mainSection = $('#main').clone(true);
每次都要获取该div初始状态的clone/copy
。
.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
一个布尔值,指示是否应复制克隆元素的所有子级的事件处理程序和数据。
您可以采取几种方法:
在更新之前缓存#main
的内容。 这只给您元素的内容,而没有元素:
mainsectionContents = $('#main').html();
或在更新之前缓存#main
的副本。 这将为您提供内容以及元素,并根据您可能想要复制的其他内容随意检查api docs :
$mainsectionCopy = $('#main').clone();
您的问题不是您的克隆正在更改,而是您用来尝试在克隆中查找内容的选择器。 您的代码是这样的:
$($mainSection + ":not(:has(*)):not(script):contains('"+newlyAddedContent+"')");
将对象与字符串连接会把该对象变成一个字符串,只是"[object Object]"
,然后您的选择器将只查看":not(:has..."
相反,您应该使用过滤器:
$foundElement = $mainClone.filter(":not(:has(*)):not(script):contains('world')");
现在,这只会在$mainClone
查找与该过滤器匹配的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.