2015-11-13 50 views
0

我有以下代碼,哪種工作,除了我得到相同的答案在所有行上重複。jQuery .each()重複所有行的答案

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>each demo</title> 
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
<body> 

<span>(click here to change)</span> 
<table width="50%" border="0" cellspacing="2" cellpadding="2"> 
    <tr> 
    <th scope="col">Part Number</th> 
    <th scope="col">Result</th> 
    </tr> 
    <tr> 
    <td id="pn">84ps01</td> 
    <td class="div1">&nbsp;</td> 
    </tr> 
    <tr> 
    <td id="pn">92K002</td> 
    <td class="div1">&nbsp;</td> 
    </tr> 
    <tr> 
    <td id="pn">68F017</td> 
    <td class="div1">&nbsp;</td> 
    </tr> 
</table> 


<script> 
$("span").click(function() { 
    var pn = $("#pn").text(); 
    $("td#pn").each(function() { 
     $(".div1").load("data.asp?prodref="+($(this).text())) 
    }); 
    }); 

</script> 
$(this).("#div1").load("data.asp?prodref="+pn+"#result"); 
</body> 
</html> 

data.asp是一個簡單的頁面,查詢使用request.querystring("prodref")返回結果的數據庫。

所以我想獲取表的每一行來查詢數據庫並返回結果。

+1

這裏'$(」。DIV1 「)。負載(」 data.asp?prodref = 「+($(this).text()))''''在'.each()'函數的每次迭代中,您將數據加載到每個具有'div1'類的元素中。這不是jQuery的錯,jQuery完全按照你的要求去做。 –

回答

2

ID應該是唯一的,不同的HTML元素不能有相同的ID,使用類。

<tr> 
    <th scope="col">Part Number</th> 
    <th scope="col">Result</th> 
    </tr> 
    <tr> 
    <td class="pn">84ps01</td> 
    <td class="div1">&nbsp;</td> 
    </tr> 
    <tr> 
    <td class="pn">92K002</td> 
    <td class="div1">&nbsp;</td> 
    </tr> 
    <tr> 
    <td class="pn">68F017</td> 
    <td class="div1">&nbsp;</td> 
    </tr> 

的jQuery:

$("td.pn").each(function() { 
     $(this).next().load("data.asp?prodref="+($(this).text())) 
}); 

你都得到同樣的答案,因爲id指的是第一個匹配元素始終。

並使用.next()去當前元素的下一個兄弟。

+0

嘗試更新的代碼。使用'.next'來尋址'.div1' – void

1

當你與線加載數據

$(".div1").load("data.asp?prodref="+($(this).text())) 

,你會看到你與div1類加載每個td的最後結果(這就是爲什麼你看到的每一行的同樣的事情) 。

你需要做什麼,而不是是找到剛纔對應的各行的div1和插入數據

的解決方案將是這個樣子:

$(document).ready(function() { 
    $("span").click(function() { 
     var pn = $("#pn").text(); 
     $(".pn").each(function() { 
      $(this).closest('tr').find(".div1").load("data.asp?prodref="+($(this).text())); 
     }); 
    }); 
}); 

上面什麼代碼正在執行,找到每個.pn並遍歷它們(.each()),然後找到遍歷DOM樹的.closest()tr,在該特定的內找到,然後將結果加載到其中。

也作爲一個供參考,id s的應該是唯一的,所以你應該切換到id="pn class="pn"

<tr> 
    <td class="pn">68F017</td> 
    <td class="div1">&nbsp;</td> 
</tr>