我有这样的HTML代码:
<li><input type="hidden" value="001" class="block-hidden-input" />
<a href="#" id="manage-1" class="manage-content-link">
<img src="images/web-block/web-block1.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
<li><input type="hidden" value="002" class="block-hidden-input" />
<a href="#" id="manage-2" class="manage-content-link">
<img src="images/web-block/web-block2.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>每个li标签都有唯一的id,其格式如下: id="manage-X“。每个用户可以有多个li标记,所以它是动态的。
另一方面,我需要这个jQuery来处理li标记:
$('#manage-1').click(function(e) {
$(this).next(".manage-content-wrap").find(".manage-content").load("file-001.php");
e.preventDefault();
});
$('#manage-2').click(function(e) {
$(this).next(".manage-content-wrap").find(".manage-content").load("file-002.php");
e.preventDefault();
});这个jQuery看起来太糟糕了。因为它是静态的,如果我有5个li标记,意味着我必须复制和粘贴5次。我不知道如何让它在jQuery上动态化。
另外,"file-001.php“和"file-002.php”是基于li的值。因此,它的格式必须是file-XXX.php (将XXX替换为li的值)。我猜这一定和RegEx有关。但我不知道该怎么做。
你知道如何基于li标记使jQuery动态化吗?谢谢!
发布于 2012-10-19 09:42:22
尝试将选择器更改为基于类。然后,您只需要找到一种方法来确定要加载哪个文件。下面的示例假设隐藏输入的值包含要加载的文件号:
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden"].block-hidden-input').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});发布于 2012-10-19 09:43:19
尝试以下方法,请注意,"file-00"+this.id.split('-')[1]+".php"只能满足file-001.php到file-009.php的要求,但您应该能够计算出大于9的值
$('[id^=manage-').click(function(e) {
$(this).next(".manage-content-wrap").find(".manage-content").load("file-00"+this.id.split('-')[1]+".php");
e.preventDefault();
});发布于 2012-10-19 09:42:08
尝试使用for循环。
for (var i = 0; i < numberOfFiles; i++)
{
$('#manage-'+i).click(function(e) {
$(this).next(".manage-content-wrap").find(".manage-content").load("file-00"+i+".php");
e.preventDefault();
});
}https://stackoverflow.com/questions/12966183
复制相似问题