2011-11-23 75 views
1

我正在尝试为我的网站上的帖子创建评论表单。我想创建一个链接,点击时显示评论表单。反过来,每页会有多个帖子,因此每个链接都是唯一的。我想使用不显眼的JavaScript来实现这一点,但我对如何在JQuery中使用唯一标识感到困惑。JQuery不显眼地通过唯一ID获取链接

例如:

<a href="#" id="comment_1234">Comment</a> 

<div id="comment_form_1234"> 
    form goes here 
</div> 

$("#comment_?").click(function(){ 
    $("#comment_form_?").show(); 
}); 

得到任何帮助。

谢谢你,

布赖恩

回答

3

我想构建这样的HTML:

<a href="#" class="comment" data-id="1234">Comment</a> 

<div class="comment_form" data-id="1234"> 
    form goes here 
</div> 

有了这个脚本:

$(".comment").on('click', function(){ 
    $('.comment_form[data-id="' + $(this).attr('data-id') + '"]').show(); 
}); 
+1

您可以用'$(本)。数据( 'ID')的''而不是$(本).attr乐表单区域

<div class="comment_form" data-id=""> </div> 

( '数据ID')'。更好地看看... – Roman

+0

只是使用$(this).next(.comment_form')。show(); ? –

+0

该解决方案运行良好。谢谢大家的帮助。 – Brian

0

你可以尝试 -

$('a[id^="comment_"]').click(function(){ 
    $("#" + this.id.replace("comment_","comment_form_")).show(); 
}); 

这应该火为您的评论的链接,就可以操纵单击元素的ID,以显示相关形式。

演示 - http://jsfiddle.net/Zjs92/

0

为什么不只是有

<a href="#" class="comment" data-id="1234">Comment</a> 

和唱使用jQuery这样

$('.comment').on('click', function(e) { 
    $('.comment_form').attr('data-id', $(this).attr('data-id')).show(); 

    if (e.preventDefault) { 
     e.preventDefault(); 
    } 
    return false; 
}); 
在新的jQuery版本