如何使用jQuery解决动态加载页面中的重复对象?

我想在动态加载内容中解决重复对象。 请查看以下源代码以便于理解。

具有1个动态加载内容的基页HTML

 
>
Dynamic Content will be placed inside this.

对于此页面标题中的脚本,可以很容易地选择“general-div”对象,如下面的代码。

  $('#general-div') 

在placeholder1中选择“inner-div”对象非常容易。 所以我可以使用下面的代码进行选择。

  $('.inner-div') 

上面的代码可以完美地运行。 但是,当同一文档中有多个重复对象(如下面的HTML)时,我无法使用上述代码。 上面的代码将返回2个不符合我想要的对象。

基页HTML – 加载另一个动态加载内容后

  
>
Dynamic Content will be placed inside this.
Dynamic Content will be placed inside this.

可能的解决方案1

我必须在动态加载内容中创建指定的jQuery对象foreach脚本,如下面的代码。

  // Deep copy for jQuery object. var specfiedjQueryObj = $.extend(true, {}, jQuery); // modify find function in jQuery object. specfiedjQueryObj.fn.find = function(selector) { // by adding placeholder selector before eval result. return new specfiedjQueryObj.fn.old_find('#placeholder1 ' + selector); }; // So, I can select any object in dynamic loading content. (function($) { // This result must be 1 object. $('.div1'); })(temp); 

尽管如此,这个解决方案应该很有效。 但我发现jQuery是一个非常复杂的对象。 我尝试使用它时发现了很多错误。

你有什么想法解决这个问题吗?

PS。 PlaceHolder Id不是固定ID。 所以,在选择器规则中修复它是不可能的。 而且,我不完全知道文件中的元素和位置(第一个,最后一个或中间)的数量。 由于动态加载内容将在很多页面上显示。

$('div[id^=placeholder]:last')怎么样?

选择器/ attrubuteStartsWith

您可以简单地使用$('.innerdiv:first')来获取第一个或$('.inner-div:last')来获取最后一个。 或者,如果你有多个并想要选择一个特定的$('.inner-div:nth(x)') ,其中x是项目的索引。

以下函数将处理来自部分加载视图页面的数据,并为脚本中的每个jQuery选择器添加指定的上下文。 这个答案效果很好。 但是,它不支持外部脚本文件。

 function renderPartialView(control, data) { // For detecting all script tag in loaded data. var reExtractScript = /( 

好的,让我们来谈谈你的HTML示例。 我添加了一类占位符,稍后在id中添加了一个破折号。

 
Dynamic Content will be placed inside this.
baz
zip
action
Dynamic Content will be placed inside this.
foo
bar
action

现在我可以使用$('.placeholder a.action').bind('click', ... );将事件绑定到每个链接$('.placeholder a.action').bind('click', ... ); 如果我希望将此事件发送到页面上所有未来的html块,我会执行$('.placeholder a.action').live('click', ... );

此代码将事件附加到这些链接, var语句可以捕获id或

的内部文本。 通过这种方式,您没有碰撞的id属性值,但您可以使用类占位符遍历div的操作。

 $('.placeholder a.action').live('click', function(){ // get the id var id = $(this).parents('div.placeholder').attr('id').split('-')[1]; // get the text inside the div with class inner-div var inner_div = $(this).parents('div.placeholder').children('.inner-div').text(); // get the text inside the div with class div1 var div1 = $(this).parents('div.placeholder').children('.div1').text(); return false; });