javascript repeat action
how to do a same loop action? thank you.
开发者_StackOverflow社区$('a.level').click(function() {
var level = $(this).parent('li').attr("class");
var nxvl = parseInt(level)+1;
var dir = $(this).html();
var curr = $(this);
var data = new Object();
data.n = new Date().getTime();
data.act = "getdirectory";
data.level = level;
data.direct = dir;
var str = $.toJSON(data);
$.post('ajax.php', { str: str }, function(result){
var data = eval('('+obj.data+')');
var html = [];
$.each(data, function(key, value) {
html[key] = "<li class='"+nxvl+"'><a href='javascript:void(0);' title='' class='level'>"+eval(value)+"</a><ul></ul></li>";
});
$(curr).next('ul').html(html.join(""));
$('a.level').click(function() {
// do the same action
}
});
return(false);
});
In this case, you probably want to use live handlers. Change your outer:
$('a.level').click(function() {
...
}
To:
$('a.level').live('click', function() {
...
}
Then you don't worry about adding new click handlers after you've updated the HTML in $(curr).next('ul').html(...)
Try moving the function logic out of the anonymous function and into a named function.
So instead of:
$('element').click(function(){ /* logic */ });
You would have:
function myFunc() { /* logic */ }
$('element').click(myFunc);
That way, within the function you can call the function again, or in your case, attach it to another element you have just created.
精彩评论