2011-11-23 72 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版本