2015-11-13 87 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>