jQuery set each problem
i have a problem with an $.each in a jQuery function, as I have the following function:
function set_max(unit) {
var max = parseInt($("#"+unit+"_area").html().replace('(','').replace(')',''));
if (max > 0) {
$("[name="+unit+"]").val(max);
$("[name=area]").html('(0)');
} else {
var val = $("#"+unit+"_area").attr('max');
$("[name="+unit+"]").val('');
$("#"+unit开发者_StackOverflow+"_area").html('('+val+')');
$.each($("[name=area]"),function(){
var caller = $(this).attr('id');
vall = $("#"+caller+"_area").attr('max');
$(caller).html('('+vall+')');
});
}
}
But the each part doesnt work, as the .html() parts from the link remain 0. The links are like this:
<a id="spear_area" name="area" max="5812" href="javascript:set_max('spear');">(5812)</a>
Try using the regular each
instead. $.fn.each is designed for iterating over jQuery objects whereas $.each iterates over regular objects/arrays.
$("[name=area]").each(function(){
var caller = $(this).attr('id');
vall = $("#"+caller+"_area").attr('max');
$(caller).html('('+vall+')');
});
The syntax of $.each() is incorrect:
.each( function(index, Element) ) Returns: jQuery
The variable caller isn't referencing the jQuery object correctly, you should add the "#" before the ID in either of the locations below:
var caller = "#" + $(this).attr('id');
OR
$("#" + caller).html('('+vall+')');
Your code should become:
function set_max(unit) {
var max = parseInt($("#"+unit+"_area").html().replace('(','').replace(')',''));
if (max > 0) {
$("[name="+unit+"]").val(max);
$("[name=area]").html('(0)');
} else {
var val = $("#"+unit+"_area").attr('max');
$("[name="+unit+"]").val('');
$("#"+unit+"_area").html('('+val+')');
$("a[name=area]").each(function() {
var caller = "#" + $(this).attr('id');
vall = $("#"+caller+"_area").attr('max');
$(caller).html('('+vall+')');
});
}
}
精彩评论