2012-09-03 18 views
0

我有這樣的重複代碼。使用jquery從頁面上的許多重複類中獲取特定元素

<div class='commentfloatleft'> 
       <button type='button' class='button2' onclick='upvote($id8)'> 
        <img src='images/likebutton.png' class='upvoteimage' width='12' height='12' alt='PearlSquirrel'/> 
       </button> 
       <button type='button' class='button2' onclick='downvote($id8)'> 
        <img src='images/unlikebutton.png' width='12' height='12' alt='PearlSquirrel'/> 
       </button> 
      </div> 

當我點擊了給予好評的onclick代碼是這樣的:

function upvote(box){ 
$(this).siblings('.upvoteimage').load('upvote.php?box=' + box); 
} 

我想盡一切辦法得到這個工作。 get函數正在工作,但在「.upvoteimage」中看不到任何更改。有誰知道如何解決這個問題。幫助將不勝感激。謝謝。

+0

獲得按鈕解僱他們需要通過'

' – ClydeFrog

+0

不真實的包圍,這只是爲了讓形式解僱。 –

+0

他已經有(內聯,不是最佳實踐,但它的工作原理) –

回答

2

試試這個方法:一類「給予好評」設置爲你的「按鈕」元素:

<div class='commentfloatleft'> 
       <button type='button' class='button2 upvote' id='$id8'> 
        <img src='images/likebutton.png' class='upvoteimage' width='12' height='12' alt='PearlSquirrel'/> 
       </button> 
       <button type='button' class='button2' onclick='downvote()'> 
        <img src='images/unlikebutton.png' width='12' height='12' alt='PearlSquirrel'/> 
       </button> 
      </div>​ 

,並使用此JS代碼:

$(".upvote").on("click",function(){ 
    var box=$(this).attr("id"); 
    $(this).find('.upvoteimage').attr("src",'upvote.php?box=' + box); 
    return false; 
}​);​ 
+0

這工作完美。對於遲到的回覆抱歉。 – Eggo

+0

不客氣:) – khomyakoshka

2

你的代碼表示兄弟姐妹,但.upvoteimage不是兄弟姐妹,而是孩子。嘗試使用find/children代替。

而$(this)可能不存在於函數中。也許你應該將onclick事件轉移到腳本塊。 jQuery有一些很棒的功能,不能使用內聯代碼。

+0

這似乎仍然不起作用。 – Eggo

+0

Ashirvad Singh回答了完整的包裝(只是還沒有解釋它) –

0

你正在引用按鈕的同級,併爲類upvoteimage的過濾。

你想要做什麼是參考了兄弟姐妹,然後選擇他們的階級upvoteimage的孩子:

$(this).siblings('.button2').children('.upvoteimage').load('upvote.php?box=' + box); 
2

試試這個

HTML

<div class='commentfloatleft'> 
        <button type='button' class='button2' onclick='upvote(this,\x27$id8\x27)'> 
         <img src='images/likebutton.png' class='upvoteimage' width='12' height='12' alt='PearlSquirrel'/> 
        </button> 
        <button type='button' class='button2' onclick='downvote($id8)'> 
         <img src='images/unlikebutton.png' width='12' height='12' alt='PearlSquirrel'/> 
        </button> 
       </div> 

jQuery代碼:

function upvote(obj,box){ 
$(obj).children('.upvoteimage').load('upvote.php?box=' + box); 
} 
0

它的孩子不是兄弟那Ÿ它是不會發生

你可以嘗試

$(this).siblings('.button2' > '.upvoteimage') 

我覺得有些什麼樣的,這將工作

0

您應該使用.on()綁定事件,而不是在線進行。

在您的upvote功能this是窗口對象不是按鈕被點擊。

與upvote類img是按鈕的孩子不是兄弟姐妹。

你不能什麼加載到img標籤,它的空標籤

相關問題