防止元素更新- JQuery

Prevent element from updating - JQuery

本文关键字:JQuery 更新 元素      更新时间:2023-09-26

我选择了一个页面元素:

$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来说明我的观点:

http://jsfiddle.net/VEQ2E/2/


问题就在这一行:(foundElement = $美元mainSection +":没有(:有(*)):没有(脚本):包含("+ newlyAddedContent +")");

它总是搜索整个文档,当我这样做的时候

您可以使用.clone(true):

$mainSection = $('#main').clone(true);

每次取div初始状态的clone/copy

注意:

.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )

withdataanddevents: Boolean(默认值:false)

deepWithDataAndEvents:布尔值(默认:withDataAndEvents的值)

一个布尔值,指示是否应该复制克隆元素的所有子元素的事件处理程序和数据。

你的问题不是你的克隆被改变了,而是你正在使用的选择器,试图在克隆中找到一些东西。你的代码是这样的:

$($mainSection + ":not(:has(*)):not(script):contains('"+newlyAddedContent+"')");

将对象与字符串连接将对象转换为字符串,简单地"[object Object]",然后选择器将只查看":not(:has..."

相反,你应该使用filter:
$foundElement = $mainClone.filter(":not(:has(*)):not(script):contains('world')");

这将只在您的$mainClone中查找与该过滤器匹配的项目。

JSFiddle

您可以采用以下几种方法:

在更新前缓存#main的内容。这将只提供元素的内容而不包含元素。:

mainsectionContents = $('#main').html();

或在更新之前缓存#main的副本。这将为您提供内容和元素,根据您想要复制的其他内容,请随意检查api文档:

$mainsectionCopy = $('#main').clone();