实例详解jQuery结合GridView控件的使用方法

2020-05-27 18:10:43易采站长站整理

</asp:GridView>
</div>
</form>
</body>

关键的在页面的head部分,输入如下代码就可以实现如图效果了。


<script src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=GridView1.ClientID%>").find("tr td input[type=checkbox]").each(function () {
$(this).bind("click", function () {
if (this.checked) {
var id = $(this).parent().parent().find("span[id*=lblId]").text();
var num1 = $(this).parent().parent().find("span[id*=lblNum1]").text();
var num2 = $(this).parent().parent().find("span[id*=lblNum2]").text();

var result = (parseFloat(num1) + parseFloat(num2)) / 2;
$(this).parent().parent().find("input[id*=avg_value]").val(result);
} else {
$(this).parent().parent().find("input[id*=avg_value]").val("");
}
});
});
});
</script>

你会发现jQuery的代码读着很轻松,很容易理解。而且代码也很优美,最关键的是兼容性很好。
再附一个简单点的例子,这是一个静态html页面,看jQuery是如何发挥威力的。效果是点击每一行的按钮时,弹出当前行的text里面的value。


<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$(function(){
$("table tr td").each(function(){
$(this).find("[type=button]").click(function(){
alert($(this).parent().parent().find("[type=text]").val());
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>1</td>
<td><input type=text value="数据1" /></td>
<td><input type=button onclick="GetTest()" value="获取" /></td>
</tr>
<tr>
<td>2</td>
<td><input type=text value="数据2" /></td>
<td><input type=button onclick="GetTest()" value="获取" /></td>
</tr>
</table>
</body>
</html>

试想,如果我们用js去做,将会很麻烦,而且还要考虑各种浏览器的兼容性。看到这里不得不感叹一句,jQuery虽然短小,但是相当强大啊。