这个问题与我昨天问的另一个问题有关,它的链接是:通过ajax将jquery中的HTML解析为元素,并替换页面上相应的
基本上,我想用ajax调用php页面,并用页面上相应的元素替换响应中的元素。我得到了以下函数的答案:
$(data ).filter('.maindiv').each(function (index)
/* "this" is the current div in response*/
$('#'+this.id).replaceWith(this);
});
当我想要替换的div有一个正则id=时,上面的函数很糟糕,但如果使用像gid=这样的自定义属性,它就不起作用了。我该怎么解决这个问题??
感谢
使用attr作为自定义属性,而不是使用this.id
,您可以使用$(this).attr("YourAttr")
;
$(data ).filter('.maindiv').each(function (index)
/* "this" is the current div in response*/
$('#'+$(this).attr('gid')).replaceWith(this);
});
您可以使用以下选项选择具有gid属性的节点:
$('[gid]').replaceWith(this);
通过只选择具有您想要的的gid值的节点,您甚至可以更精确
$('[gid="hello"]').replaceWith(this);
希望它能帮助
对于数据,您可以使用自定义属性。HTML5指定了data-
属性的使用。最酷的是,这也适用于HTML4!jQuery可以使用data方法读取它。
我推荐:
<div class="maindiv" data-grid="myGrid">...</div>
$(data).filter('.maindiv').each(function (index)
$('#'+$(this).data('gid')).replaceWith(this);
});