jquery异步加载获得json一个list对象.
写了个for循环
[code="java"][
function loadUsers(json) {
var obj = JSON.parse(json);
var list = obj.list;
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
var truename = list[i].truename;
var type = list[i].type;
$("#inserthtml").after("<tr><td>" + truename + "</td><td><input type='radio' id='" + id + "_A' name='radio_"
+ id + "' value='0'>未激活" + "<input type='radio' id='" + id
+ "_B' name='radio_" + id
+ "' value='1'>管理员<input type='radio' id='" + id
+ "_C' name='radio_" + id + "' value='2'>项目主管"
+ "<input type='radio' id='" + id + "_D' name='radio_" + id
+ "' value='3'>员工 </td><td><a href='/IdeaYapai_20100505/DeleteUserServlet?id=" + id
+ "' onclick='return confirm(\"确定删除?\");' >删除</a></td><td><input type='button' id='updatetype" + id
+ "' value='更新权限'/></td></tr>")
switch (type) {
case 0 :
$("#" + id + "_A").attr("checked", "true");
break;
case 1 :
$("#" + id + "_B").attr("checked", "true");
break;
case 2 :
$("#" + id + "_C").attr("checked", "true");
break;
case 3 :
$("#" + id + "_D").attr("checked", "true");
break;
}
$("#updatetype" + id).click(function() {
$.ajax({
url : 'UpdateTypeServlet',
cache : false,
type : 'post',
dataType : 'html',
data : 'userid='
+ id
+ '&newtype='
+ $("input[name=radio_" + id + "][checked]")
.val()
});
});
}
}
[/code]
问题是:每添加一行
就给里的button添加一个事件,但是这样的事件获得的id和newtype都是最后一个元素的.补充一下:在button按钮的前面添加一个隐藏域。
[code="html"]
ps:用记事本手写代码,可能存在某些语法错误
[quote]如何给每一个按钮添加动作事件[/quote]
[b]
获取ID为inserthtml的元素下的所有 button 元素,然后再添加。试试这样,其中的id参数,可以通过this来获取到[/b]
[code="js"]
$("#inserthtml buttion").click(
function(this){
//..........
}
)[/code]
写了个错别字,不好意思:
[code="js"]$("#inserthtml button").click(
function(this){
//..........
}
)[/code]
[code="java"]$("#updatetype" + id).bind("click",function(){
$.ajax({
url : 'UpdateTypeServlet',
cache : false,
type : 'post',
dataType : 'html',
data : 'userid='
+ id
+ '&newtype='
+ $("input[name=radio_" + id + "][checked]")
.val()
});
})[/code]
每一个ID绑定一个事件, 你直接用CLICK是要循环就执行这个吗?循环就执行可以用,如果要以后用就用绑定事件!
在function中使用this,来获取id的值
[code="java"]$("#inserthtml buttion").click(
function(){
//..........
alert(this.id);
}
)[/code]
[b]你那种写法jquery不支持;[/b]
[b]解决办法是:将click事件写在button里面,[/b]如下:
[code="html"]
[b]如下updateType方法的实现:[/b]
[code="JavaScript"]function updateType(){
var id = $(this).prev().val();
$.ajax({
url : 'UpdateTypeServlet',
cache : false,
type : 'post',
dataType : 'html',
data : 'userid='
+ id
+ '&newtype='
+ $("input[name=radio_" + id + "][checked]").val()
});
}[/code]